← Componentes

Event Calendar

Calendario de eventos completo con cuatro modos de visualización (mes, semana, día y agenda). Diseñado bajo la estética editorial de Kenza: hairlines de 1px, tipografía tabular refinada, filtrado dinámico de etiquetas, tarjeta de detalle en modal accesible y sin dependencias pesadas externas.

Playground interactivo

octubre de 2026

Filtrar:
lun
mar
mié
jue
vie
sáb
dom
28
29
30
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
161 evento
17
181 evento
19
202 eventos
211 evento
22
231 evento
24
251 evento
26
27
28
29
30
31
1

4 Vistas Especializadas

El componente adapta su grilla y estructura al objetivo del usuario mediante la prop view:

  • Mes ('month'): Grilla clásica de semanas con cálculo preciso de días del mes anterior y siguiente. Días con múltiples eventos muestran un botón discreto ("+X más") que abre un popover flotante interactivo.
  • Semana ('week'): Grilla horaria de 24 horas con posicionamiento proporcional exacto en minutos, indicador de hora actual en tiempo real y columna lateral de horas.
  • Día ('day'): Vista de alta resolución focalizada en una sola jornada para no saturar agendas densas.
  • Agenda ('agenda'): Lista cronológica agrupada por fecha, ideal para navegación rápida en dispositivos móviles o paneles angostos.

Categorías y Variantes Semánticas

Cada evento puede tener asignada una variante de color estricta acorde a la paleta de Kenza (primary para el dorado de acento, success, danger, warning, info o muted). La barra de categorías superior permite filtrado instantáneo sin recargar la vista.

Código

"use client";

import * as React from "react";
import { cn } from "./lib/cn";
import { EASE } from "./lib/motion";
import { useDismiss } from "./lib/use-dismiss";
import { Avatar } from "./avatar";
import { Badge } from "./badge";
import { Button } from "./button";

/* ==========================================================================
   Types & Models
   ========================================================================== */

export type EventVariant = "primary" | "success" | "danger" | "warning" | "info" | "muted";
export type CalendarView = "month" | "week" | "day" | "agenda";

export interface CalendarAttendee {
  name: string;
  email?: string;
  avatarUrl?: string;
  fallback?: string;
}

export interface CalendarEvent {
  id: string;
  title: string;
  start: Date;
  end: Date;
  allDay?: boolean;
  category?: string;
  variant?: EventVariant;
  location?: string;
  description?: string;
  attendees?: CalendarAttendee[];
}

export interface CalendarCategory {
  id: string;
  label: string;
  variant: EventVariant;
}

export interface EventCalendarProps extends React.HTMLAttributes<HTMLDivElement> {
  events: CalendarEvent[];
  /** Vista actual ("month" | "week" | "day" | "agenda") */
  view?: CalendarView;
  /** Vista por defecto si no es controlado */
  defaultView?: CalendarView;
  onViewChange?: (view: CalendarView) => void;
  /** Fecha de referencia seleccionada/enfocada */
  date?: Date;
  defaultDate?: Date;
  onDateChange?: (date: Date) => void;
  /** Categorías para filtrar */
  categories?: CalendarCategory[];
  /** Categoría seleccionada en el filtro */
  selectedCategory?: string;
  onSelectCategory?: (category: string) => void;
  /** Callback al hacer clic en un evento */
  onEventClick?: (event: CalendarEvent) => void;
  /** Callback al hacer clic en una casilla de día o franja horaria */
  onSlotClick?: (date: Date, hour?: number) => void;
  /** Idioma para nombres de días, meses y formatos (default: "es") */
  locale?: string;
  /** Hora de inicio para la grilla horaria semanal/diaria (0-23, default: 8) */
  startHour?: number;
  /** Hora de fin para la grilla horaria semanal/diaria (0-23, default: 20) */
  endHour?: number;
  /** Si true, permite agregar nuevos eventos con un botón de acción */
  onAddEvent?: () => void;
}

/* ==========================================================================
   Helpers de Fecha
   ========================================================================== */

function stripTime(d: Date): number {
  return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
}

function isSameDay(a: Date, b: Date): boolean {
  return stripTime(a) === stripTime(b);
}

function isToday(d: Date): boolean {
  return isSameDay(d, new Date());
}

function formatTime(d: Date, locale = "es"): string {
  return new Intl.DateTimeFormat(locale, { hour: "2-digit", minute: "2-digit", hour12: false }).format(d);
}

function getWeekdayNames(locale: string, format: "short" | "long" | "narrow" = "short"): string[] {
  const fmt = new Intl.DateTimeFormat(locale, { weekday: format });
  return Array.from({ length: 7 }, (_, i) => {
    // 2024-01-01 fue lunes
    const d = new Date(2024, 0, 1 + i);
    return fmt.format(d);
  });
}

function getMonthName(year: number, month: number, locale: string): string {
  return new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" }).format(new Date(year, month, 1));
}

function getMonthGrid(year: number, month: number) {
  const firstWeekday = (new Date(year, month, 1).getDay() + 6) % 7; // Lunes = 0
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const daysInPrevMonth = new Date(year, month, 0).getDate();

  const cells: { date: Date; outside: boolean }[] = [];
  for (let i = firstWeekday - 1; i >= 0; i--) {
    cells.push({ date: new Date(year, month - 1, daysInPrevMonth - i), outside: true });
  }
  for (let d = 1; d <= daysInMonth; d++) {
    cells.push({ date: new Date(year, month, d), outside: false });
  }
  let next = 1;
  while (cells.length % 7 !== 0 || cells.length < 35) {
    cells.push({ date: new Date(year, month + 1, next), outside: true });
    next++;
  }
  return cells;
}

function getWeekDays(referenceDate: Date): Date[] {
  const dayOfWeek = (referenceDate.getDay() + 6) % 7; // Lunes = 0
  const monday = new Date(referenceDate);
  monday.setDate(referenceDate.getDate() - dayOfWeek);
  monday.setHours(0, 0, 0, 0);

  return Array.from({ length: 7 }, (_, i) => {
    const d = new Date(monday);
    d.setDate(monday.getDate() + i);
    return d;
  });
}

const variantStyles: Record<EventVariant, { pill: string; badge: "primary" | "success" | "danger" | "warning" | "info" | "default" }> = {
  primary: {
    pill: "bg-primary/15 text-primary border-primary/30 hover:bg-primary/25",
    badge: "primary",
  },
  success: {
    pill: "bg-success/15 text-success border-success/30 hover:bg-success/25",
    badge: "success",
  },
  danger: {
    pill: "bg-danger/15 text-danger border-danger/30 hover:bg-danger/25",
    badge: "danger",
  },
  warning: {
    pill: "bg-warning/15 text-warning border-warning/30 hover:bg-warning/25",
    badge: "warning",
  },
  info: {
    pill: "bg-info/15 text-info border-info/30 hover:bg-info/25",
    badge: "info",
  },
  muted: {
    pill: "bg-muted text-muted-foreground border-border hover:bg-muted/80",
    badge: "default",
  },
};

/* ==========================================================================
   EventDetailsModal (Visualizador de detalle de evento)
   ========================================================================== */

interface EventModalProps {
  event: CalendarEvent | null;
  onClose: () => void;
  locale?: string;
}

function EventDetailsModal({ event, onClose, locale = "es" }: EventModalProps) {
  const panelRef = React.useRef<HTMLDivElement>(null);
  useDismiss(Boolean(event), onClose, panelRef);

  if (!event) return null;

  const variant = event.variant ?? "primary";
  const badgeVariant = variantStyles[variant].badge;

  const dateStr = new Intl.DateTimeFormat(locale, {
    weekday: "long",
    day: "numeric",
    month: "long",
  }).format(event.start);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm p-4">
      <div
        ref={panelRef}
        role="dialog"
        aria-modal="true"
        className={cn(
          "w-full max-w-md rounded-lg border border-border bg-background p-6 shadow-2xl transition-all",
          EASE,
        )}
      >
        <div className="flex items-start justify-between gap-3">
          <div className="flex flex-col gap-1.5">
            {event.category && (
              <Badge variant={badgeVariant} size="sm">
                {event.category}
              </Badge>
            )}
            <h3 className="text-lg font-medium text-foreground leading-snug">{event.title}</h3>
          </div>
          <button
            type="button"
            onClick={onClose}
            aria-label="Cerrar detalle"
            className="rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
          >
            <svg className="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M18 6 6 18M6 6l12 12" />
            </svg>
          </button>
        </div>

        <div className="mt-4 flex flex-col gap-3 text-xs text-muted-foreground border-t border-b border-border/60 py-3.5">
          {/* Horario */}
          <div className="flex items-center gap-2 text-foreground">
            <svg className="h-4 w-4 text-primary shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <circle cx="12" cy="12" r="10" />
              <polyline points="12 6 12 12 16 14" />
            </svg>
            <span className="capitalize">{dateStr}</span>
            <span className="font-mono text-muted-foreground">
              {event.allDay ? "Todo el día" : `${formatTime(event.start, locale)} – ${formatTime(event.end, locale)}`}
            </span>
          </div>

          {/* Ubicación */}
          {event.location && (
            <div className="flex items-center gap-2">
              <svg className="h-4 w-4 shrink-0 text-muted-foreground" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z" />
                <circle cx="12" cy="10" r="3" />
              </svg>
              <span>{event.location}</span>
            </div>
          )}

          {/* Descripción */}
          {event.description && (
            <div className="mt-1 text-muted-foreground text-xs leading-relaxed">
              {event.description}
            </div>
          )}
        </div>

        {/* Asistentes */}
        {event.attendees && event.attendees.length > 0 && (
          <div className="mt-4">
            <h4 className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground mb-2">
              Asistentes ({event.attendees.length})
            </h4>
            <div className="flex flex-wrap gap-2">
              {event.attendees.map((att, i) => (
                <div
                  key={i}
                  className="flex items-center gap-2 rounded border border-border bg-muted/30 px-2 py-1 text-xs"
                >
                  <Avatar
                    src={att.avatarUrl}
                    fallback={att.fallback ?? att.name.slice(0, 2).toUpperCase()}
                    size="xs"
                  />
                  <span className="font-medium text-foreground">{att.name}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        <div className="mt-6 flex justify-end gap-2">
          <Button variant="outline" size="sm" onClick={onClose}>
            Cerrar
          </Button>
        </div>
      </div>
    </div>
  );
}

/* ==========================================================================
   DayEventsPopover (Para cuando hay más de 2 o 3 eventos en un día del mes)
   ========================================================================== */

interface DayEventsPopoverProps {
  date: Date;
  events: CalendarEvent[];
  onSelectEvent: (event: CalendarEvent) => void;
  onClose: () => void;
  locale?: string;
}

function DayEventsPopover({ date, events, onSelectEvent, onClose, locale = "es" }: DayEventsPopoverProps) {
  const popoverRef = React.useRef<HTMLDivElement>(null);
  useDismiss(true, onClose, popoverRef);

  const title = new Intl.DateTimeFormat(locale, { weekday: "long", day: "numeric", month: "short" }).format(date);

  return (
    <div className="fixed inset-0 z-40 flex items-center justify-center bg-background/50 backdrop-blur-xs p-4">
      <div
        ref={popoverRef}
        className={cn(
          "w-full max-w-xs rounded-md border border-border bg-background p-4 shadow-xl text-left",
          EASE,
        )}
      >
        <div className="flex items-center justify-between pb-2 border-b border-border">
          <span className="text-xs font-medium text-foreground capitalize">{title}</span>
          <button
            type="button"
            onClick={onClose}
            className="rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground"
          >
            <svg className="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M18 6 6 18M6 6l12 12" />
            </svg>
          </button>
        </div>
        <div className="mt-2.5 flex flex-col gap-1.5 max-h-60 overflow-y-auto">
          {events.map((ev) => {
            const v = ev.variant ?? "primary";
            return (
              <button
                key={ev.id}
                type="button"
                onClick={() => {
                  onSelectEvent(ev);
                  onClose();
                }}
                className={cn(
                  "flex items-center justify-between gap-2 rounded border px-2 py-1.5 text-xs text-left transition-colors",
                  variantStyles[v].pill,
                )}
              >
                <span className="font-medium truncate">{ev.title}</span>
                <span className="font-mono text-[10px] shrink-0 opacity-80">
                  {ev.allDay ? "Todo el día" : formatTime(ev.start, locale)}
                </span>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

/* ==========================================================================
   MonthView (Vista de Mes Completa)
   ========================================================================== */

function MonthView({
  date,
  events,
  onEventClick,
  onSlotClick,
  locale = "es",
}: {
  date: Date;
  events: CalendarEvent[];
  onEventClick: (ev: CalendarEvent) => void;
  onSlotClick?: (date: Date) => void;
  locale?: string;
}) {
  const year = date.getFullYear();
  const month = date.getMonth();
  const days = React.useMemo(() => getMonthGrid(year, month), [year, month]);
  const weekdays = React.useMemo(() => getWeekdayNames(locale, "short"), [locale]);
  const [popoverDate, setPopoverDate] = React.useState<Date | null>(null);

  const popoverEvents = React.useMemo(() => {
    if (!popoverDate) return [];
    return events.filter((e) => isSameDay(e.start, popoverDate));
  }, [events, popoverDate]);

  return (
    <div className="w-full select-none overflow-x-auto">
      <div className="min-w-[640px]">
        {/* Cabecera de días de la semana */}
        <div className="grid grid-cols-7 border-b border-border bg-muted/20">
          {weekdays.map((wd, i) => (
            <div
              key={i}
              className="py-2.5 text-center text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground"
            >
              {wd}
            </div>
          ))}
        </div>

        {/* Grilla de días */}
        <div className="grid grid-cols-7 border-b border-l border-border divide-x divide-y divide-border">
          {days.map(({ date: cellDate, outside }, idx) => {
            const cellEvents = events.filter((e) => isSameDay(e.start, cellDate));
            const today = isToday(cellDate);
            const visibleEvents = cellEvents.slice(0, 2);
            const hiddenCount = cellEvents.length - visibleEvents.length;

            return (
              <div
                key={idx}
                onClick={() => onSlotClick?.(cellDate)}
                className={cn(
                  "min-h-[110px] p-2 transition-colors flex flex-col justify-between group",
                  outside ? "bg-muted/10 opacity-40" : "bg-background",
                  "hover:bg-muted/20 cursor-pointer",
                )}
              >
                {/* Número del día */}
                <div className="flex items-center justify-between">
                  <span
                    className={cn(
                      "flex h-6 w-6 items-center justify-center rounded-md font-mono text-xs transition-colors",
                      today
                        ? "bg-primary font-semibold text-primary-foreground shadow-sm"
                        : "text-foreground group-hover:text-primary",
                    )}
                  >
                    {cellDate.getDate()}
                  </span>
                  {cellEvents.length > 0 && (
                    <span className="text-[10px] font-mono text-muted-foreground">
                      {cellEvents.length} {cellEvents.length === 1 ? "evento" : "eventos"}
                    </span>
                  )}
                </div>

                {/* Lista de eventos del día */}
                <div className="mt-1 flex flex-col gap-1">
                  {visibleEvents.map((ev) => {
                    const v = ev.variant ?? "primary";
                    return (
                      <button
                        key={ev.id}
                        type="button"
                        onClick={(e) => {
                          e.stopPropagation();
                          onEventClick(ev);
                        }}
                        className={cn(
                          "flex items-center gap-1.5 rounded px-1.5 py-0.5 text-left text-[11px] font-medium border truncate transition-all duration-100",
                          variantStyles[v].pill,
                        )}
                      >
                        {!ev.allDay && (
                          <span className="font-mono text-[9px] opacity-75 shrink-0">
                            {formatTime(ev.start, locale)}
                          </span>
                        )}
                        <span className="truncate">{ev.title}</span>
                      </button>
                    );
                  })}

                  {hiddenCount > 0 && (
                    <button
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        setPopoverDate(cellDate);
                      }}
                      className="mt-0.5 text-left text-[10px] font-medium text-primary hover:underline"
                    >
                      +{hiddenCount} más...
                    </button>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {popoverDate && (
        <DayEventsPopover
          date={popoverDate}
          events={popoverEvents}
          onSelectEvent={onEventClick}
          onClose={() => setPopoverDate(null)}
          locale={locale}
        />
      )}
    </div>
  );
}

/* ==========================================================================
   WeekView (Vista de Semana Horaria)
   ========================================================================== */

function WeekView({
  date,
  events,
  onEventClick,
  onSlotClick,
  startHour = 8,
  endHour = 20,
  locale = "es",
}: {
  date: Date;
  events: CalendarEvent[];
  onEventClick: (ev: CalendarEvent) => void;
  onSlotClick?: (date: Date, hour: number) => void;
  startHour?: number;
  endHour?: number;
  locale?: string;
}) {
  const weekDays = React.useMemo(() => getWeekDays(date), [date]);
  const hours = Array.from({ length: endHour - startHour + 1 }, (_, i) => startHour + i);

  return (
    <div className="w-full overflow-x-auto">
      <div className="min-w-[700px]">
        {/* Cabecera de Días de la Semana */}
        <div className="grid grid-cols-[60px_repeat(7,1fr)] border-b border-border bg-muted/20">
          <div className="p-3 text-center text-xs font-mono text-muted-foreground">GMT</div>
          {weekDays.map((d, i) => {
            const today = isToday(d);
            const dayName = new Intl.DateTimeFormat(locale, { weekday: "short" }).format(d);
            return (
              <div
                key={i}
                className={cn(
                  "p-2.5 text-center border-l border-border",
                  today && "bg-primary/5",
                )}
              >
                <div className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
                  {dayName}
                </div>
                <div
                  className={cn(
                    "mx-auto mt-1 flex h-6 w-6 items-center justify-center rounded-md font-mono text-xs font-medium",
                    today ? "bg-primary text-primary-foreground font-semibold" : "text-foreground",
                  )}
                >
                  {d.getDate()}
                </div>
              </div>
            );
          })}
        </div>

        {/* Grilla Horaria */}
        <div className="grid grid-cols-[60px_repeat(7,1fr)] divide-x divide-border">
          {/* Eje de Horas */}
          <div className="divide-y divide-border/60 bg-muted/5">
            {hours.map((h) => (
              <div key={h} className="h-16 pr-2 text-right text-[11px] font-mono text-muted-foreground pt-1">
                {String(h).padStart(2, "0")}:00
              </div>
            ))}
          </div>

          {/* Columnas de los 7 días */}
          {weekDays.map((d, dayIdx) => {
            const dayEvents = events.filter((e) => isSameDay(e.start, d));
            const today = isToday(d);

            return (
              <div
                key={dayIdx}
                className={cn(
                  "relative divide-y divide-border/60 transition-colors",
                  today ? "bg-primary/[0.02]" : "bg-background",
                )}
              >
                {hours.map((h) => (
                  <div
                    key={h}
                    onClick={() => onSlotClick?.(d, h)}
                    className="h-16 hover:bg-muted/20 cursor-pointer transition-colors"
                  />
                ))}

                {/* Eventos superpuestos calculados según hora */}
                {dayEvents.map((ev) => {
                  const startH = ev.start.getHours() + ev.start.getMinutes() / 60;
                  const endH = ev.end.getHours() + ev.end.getMinutes() / 60;
                  const v = ev.variant ?? "primary";

                  // Calcular posición top y altura relativa
                  const topOffset = Math.max(0, startH - startHour) * 64; // 64px = 16 (h-16) * 4px
                  const durationHours = Math.max(0.5, endH - startH);
                  const height = durationHours * 64;

                  return (
                    <button
                      key={ev.id}
                      type="button"
                      style={{ top: `${topOffset}px`, height: `${height}px` }}
                      onClick={(e) => {
                        e.stopPropagation();
                        onEventClick(ev);
                      }}
                      className={cn(
                        "absolute inset-x-1 z-10 flex flex-col overflow-hidden rounded border p-1.5 text-left text-xs transition-transform duration-100 hover:scale-[1.02]",
                        variantStyles[v].pill,
                      )}
                    >
                      <span className="font-medium truncate leading-tight">{ev.title}</span>
                      <span className="font-mono text-[10px] opacity-80">
                        {formatTime(ev.start, locale)} – {formatTime(ev.end, locale)}
                      </span>
                      {ev.location && (
                        <span className="text-[10px] opacity-75 truncate mt-auto">
                          📍 {ev.location}
                        </span>
                      )}
                    </button>
                  );
                })}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

/* ==========================================================================
   DayView (Vista de Día Detallada)
   ========================================================================== */

function DayView({
  date,
  events,
  onEventClick,
  onSlotClick,
  startHour = 8,
  endHour = 20,
  locale = "es",
}: {
  date: Date;
  events: CalendarEvent[];
  onEventClick: (ev: CalendarEvent) => void;
  onSlotClick?: (date: Date, hour: number) => void;
  startHour?: number;
  endHour?: number;
  locale?: string;
}) {
  const hours = Array.from({ length: endHour - startHour + 1 }, (_, i) => startHour + i);
  const dayEvents = events.filter((e) => isSameDay(e.start, date));
  const fullDateStr = new Intl.DateTimeFormat(locale, {
    weekday: "long",
    day: "numeric",
    month: "long",
    year: "numeric",
  }).format(date);

  return (
    <div className="w-full">
      <div className="p-4 border-b border-border bg-muted/20 flex items-center justify-between">
        <div>
          <span className="text-xs uppercase tracking-wider text-muted-foreground font-medium">Agenda Diaria</span>
          <h3 className="text-base font-semibold text-foreground capitalize mt-0.5">{fullDateStr}</h3>
        </div>
        <Badge variant={isToday(date) ? "primary" : "default"}>
          {isToday(date) ? "Hoy" : `${dayEvents.length} eventos`}
        </Badge>
      </div>

      <div className="grid grid-cols-[80px_1fr] divide-x divide-border">
        {/* Horas */}
        <div className="divide-y divide-border/60 bg-muted/5">
          {hours.map((h) => (
            <div key={h} className="h-20 pr-3 text-right text-xs font-mono text-muted-foreground pt-1.5">
              {String(h).padStart(2, "0")}:00
            </div>
          ))}
        </div>

        {/* Franja horaria interactiva con eventos */}
        <div className="relative divide-y divide-border/60 bg-background">
          {hours.map((h) => (
            <div
              key={h}
              onClick={() => onSlotClick?.(date, h)}
              className="h-20 hover:bg-muted/15 cursor-pointer transition-colors"
            />
          ))}

          {dayEvents.map((ev) => {
            const startH = ev.start.getHours() + ev.start.getMinutes() / 60;
            const endH = ev.end.getHours() + ev.end.getMinutes() / 60;
            const v = ev.variant ?? "primary";

            const topOffset = Math.max(0, startH - startHour) * 80;
            const duration = Math.max(0.6, endH - startH);
            const height = duration * 80;

            return (
              <button
                key={ev.id}
                type="button"
                style={{ top: `${topOffset}px`, height: `${height}px` }}
                onClick={(e) => {
                  e.stopPropagation();
                  onEventClick(ev);
                }}
                className={cn(
                  "absolute inset-x-3 z-10 flex flex-col justify-between rounded-md border p-3 text-left transition-all hover:scale-[1.01] shadow-sm",
                  variantStyles[v].pill,
                )}
              >
                <div>
                  <div className="flex items-center justify-between gap-2">
                    <span className="font-semibold text-sm text-foreground truncate">{ev.title}</span>
                    <span className="font-mono text-xs opacity-80">
                      {formatTime(ev.start, locale)} – {formatTime(ev.end, locale)}
                    </span>
                  </div>
                  {ev.description && (
                    <p className="mt-1 text-xs opacity-85 line-clamp-2 leading-relaxed">{ev.description}</p>
                  )}
                </div>

                <div className="flex items-center justify-between mt-2 pt-2 border-t border-border/40 text-xs">
                  {ev.location && <span className="opacity-80">📍 {ev.location}</span>}
                  {ev.attendees && ev.attendees.length > 0 && (
                    <div className="flex -space-x-1.5 ml-auto">
                      {ev.attendees.slice(0, 3).map((att, i) => (
                        <Avatar
                          key={i}
                          src={att.avatarUrl}
                          fallback={att.fallback ?? att.name.slice(0, 2).toUpperCase()}
                          size="xs"
                        />
                      ))}
                    </div>
                  )}
                </div>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

/* ==========================================================================
   AgendaView (Vista de Lista / Feed Cronológico)
   ========================================================================== */

function AgendaView({
  events,
  onEventClick,
  locale = "es",
}: {
  events: CalendarEvent[];
  onEventClick: (ev: CalendarEvent) => void;
  locale?: string;
}) {
  // Agrupar eventos por fecha
  const groupedEvents = React.useMemo(() => {
    const sorted = [...events].sort((a, b) => a.start.getTime() - b.start.getTime());
    const groups: { date: Date; items: CalendarEvent[] }[] = [];

    sorted.forEach((ev) => {
      const existing = groups.find((g) => isSameDay(g.date, ev.start));
      if (existing) {
        existing.items.push(ev);
      } else {
        groups.push({ date: ev.start, items: [ev] });
      }
    });

    return groups;
  }, [events]);

  if (groupedEvents.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center p-14 text-center">
        <div className="flex h-10 w-10 items-center justify-center rounded-md border border-border bg-muted/30 text-muted-foreground mb-3">
          <svg className="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <rect width="18" height="18" x="3" y="4" rx="2" ry="2" />
            <line x1="16" x2="16" y1="2" y2="6" />
            <line x1="8" x2="8" y1="2" y2="6" />
            <line x1="3" x2="21" y1="10" y2="10" />
          </svg>
        </div>
        <h4 className="text-sm font-medium text-foreground">No hay eventos programados</h4>
        <p className="mt-1 text-xs text-muted-foreground max-w-xs">
          No se encontraron eventos activos en este período o bajo el filtro seleccionado.
        </p>
      </div>
    );
  }

  return (
    <div className="flex flex-col divide-y divide-border">
      {groupedEvents.map((group, gIdx) => {
        const today = isToday(group.date);
        const dayLabel = new Intl.DateTimeFormat(locale, { weekday: "long", day: "numeric", month: "long" }).format(group.date);

        return (
          <div key={gIdx} className="p-4 sm:p-6 flex flex-col md:flex-row md:items-start gap-4">
            {/* Cabecera del día */}
            <div className="md:w-52 shrink-0 flex items-center md:flex-col md:items-start gap-2">
              <span className="font-semibold text-sm capitalize text-foreground">{dayLabel}</span>
              {today && (
                <Badge variant="primary" size="sm">
                  Hoy
                </Badge>
              )}
            </div>

            {/* Lista de eventos del día */}
            <div className="flex-1 flex flex-col gap-2.5">
              {group.items.map((ev) => {
                const v = ev.variant ?? "primary";
                return (
                  <div
                    key={ev.id}
                    onClick={() => onEventClick(ev)}
                    className={cn(
                      "flex flex-col sm:flex-row sm:items-center justify-between gap-3 rounded-lg border p-3.5 transition-all cursor-pointer hover:border-primary/40 hover:bg-muted/20",
                      variantStyles[v].pill,
                    )}
                  >
                    <div className="flex flex-col gap-1">
                      <div className="flex items-center gap-2">
                        {ev.category && <Badge variant={variantStyles[v].badge} size="sm">{ev.category}</Badge>}
                        <h4 className="text-sm font-semibold text-foreground leading-tight">{ev.title}</h4>
                      </div>
                      {ev.description && (
                        <p className="text-xs text-muted-foreground line-clamp-1">{ev.description}</p>
                      )}
                      {ev.location && (
                        <span className="text-[11px] text-muted-foreground">📍 {ev.location}</span>
                      )}
                    </div>

                    <div className="flex items-center gap-3 sm:self-center">
                      <span className="font-mono text-xs text-foreground font-medium shrink-0">
                        {ev.allDay ? "Todo el día" : `${formatTime(ev.start, locale)} – ${formatTime(ev.end, locale)}`}
                      </span>
                      {ev.attendees && ev.attendees.length > 0 && (
                        <div className="flex -space-x-1.5">
                          {ev.attendees.slice(0, 3).map((att, i) => (
                            <Avatar
                              key={i}
                              src={att.avatarUrl}
                              fallback={att.fallback ?? att.name.slice(0, 2).toUpperCase()}
                              size="xs"
                            />
                          ))}
                        </div>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        );
      })}
    </div>
  );
}

/* ==========================================================================
   EventCalendar (Componente Principal)
   ========================================================================== */

export function EventCalendar({
  events,
  view: controlledView,
  defaultView = "month",
  onViewChange,
  date: controlledDate,
  defaultDate,
  onDateChange,
  categories,
  selectedCategory: controlledCat,
  onSelectCategory,
  onEventClick,
  onSlotClick,
  onAddEvent,
  locale = "es",
  startHour = 8,
  endHour = 20,
  className,
  ...props
}: EventCalendarProps) {
  // Control de vista
  const [uncontrolledView, setUncontrolledView] = React.useState<CalendarView>(defaultView);
  const isViewControlled = controlledView !== undefined;
  const view = isViewControlled ? controlledView : uncontrolledView;

  const setView = React.useCallback(
    (next: CalendarView) => {
      if (!isViewControlled) setUncontrolledView(next);
      onViewChange?.(next);
    },
    [isViewControlled, onViewChange],
  );

  // Control de fecha activa
  const [uncontrolledDate, setUncontrolledDate] = React.useState<Date>(defaultDate ?? new Date());
  const isDateControlled = controlledDate !== undefined;
  const activeDate = isDateControlled ? controlledDate : uncontrolledDate;

  const setDate = React.useCallback(
    (next: Date) => {
      if (!isDateControlled) setUncontrolledDate(next);
      onDateChange?.(next);
    },
    [isDateControlled, onDateChange],
  );

  // Filtro de categoría
  const [uncontrolledCat, setUncontrolledCat] = React.useState<string>("all");
  const isCatControlled = controlledCat !== undefined;
  const currentCategory = isCatControlled ? controlledCat : uncontrolledCat;

  const setCategory = React.useCallback(
    (next: string) => {
      if (!isCatControlled) setUncontrolledCat(next);
      onSelectCategory?.(next);
    },
    [isCatControlled, onSelectCategory],
  );

  // Modal de detalle
  const [activeEvent, setActiveEvent] = React.useState<CalendarEvent | null>(null);

  // Navegación
  const handlePrev = () => {
    const next = new Date(activeDate);
    if (view === "month") next.setMonth(next.getMonth() - 1);
    else if (view === "week") next.setDate(next.getDate() - 7);
    else if (view === "day") next.setDate(next.getDate() - 1);
    else if (view === "agenda") next.setMonth(next.getMonth() - 1);
    setDate(next);
  };

  const handleNext = () => {
    const next = new Date(activeDate);
    if (view === "month") next.setMonth(next.getMonth() + 1);
    else if (view === "week") next.setDate(next.getDate() + 7);
    else if (view === "day") next.setDate(next.getDate() + 1);
    else if (view === "agenda") next.setMonth(next.getMonth() + 1);
    setDate(next);
  };

  const handleToday = () => {
    setDate(new Date());
  };

  // Filtrado de eventos por categoría
  const filteredEvents = React.useMemo(() => {
    if (!currentCategory || currentCategory === "all") return events;
    return events.filter((e) => e.category === currentCategory);
  }, [events, currentCategory]);

  // Formato del título del período
  const periodTitle = React.useMemo(() => {
    if (view === "month") {
      return getMonthName(activeDate.getFullYear(), activeDate.getMonth(), locale);
    }
    if (view === "week") {
      const week = getWeekDays(activeDate);
      const startDay = week[0].getDate();
      const endDay = week[6].getDate();
      const monthLabel = new Intl.DateTimeFormat(locale, { month: "short", year: "numeric" }).format(week[6]);
      return `${startDay} – ${endDay} ${monthLabel}`;
    }
    if (view === "day") {
      return new Intl.DateTimeFormat(locale, { weekday: "long", day: "numeric", month: "long", year: "numeric" }).format(activeDate);
    }
    return new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" }).format(activeDate);
  }, [activeDate, view, locale]);

  return (
    <div
      className={cn(
        "flex flex-col w-full rounded-lg border border-border bg-background shadow-xs",
        className,
      )}
      {...props}
    >
      {/* Barra de herramientas superior */}
      <div className="flex flex-col gap-3 p-4 sm:flex-row sm:items-center sm:justify-between border-b border-border">
        {/* Controles de Navegación y Fecha */}
        <div className="flex flex-wrap items-center gap-2">
          <Button variant="outline" size="sm" onClick={handleToday}>
            Hoy
          </Button>

          <div className="flex items-center gap-0.5 rounded-md border border-border bg-background p-0.5">
            <button
              type="button"
              onClick={handlePrev}
              aria-label="Período anterior"
              className="flex h-7 w-7 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
            >
              <svg className="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="m15 18-6-6 6-6" />
              </svg>
            </button>
            <button
              type="button"
              onClick={handleNext}
              aria-label="Período siguiente"
              className="flex h-7 w-7 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
            >
              <svg className="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="m9 18 6-6-6-6" />
              </svg>
            </button>
          </div>

          <h2 className="text-base font-semibold capitalize text-foreground sm:ml-2">
            {periodTitle}
          </h2>
        </div>

        {/* Selector de Vistas y Botón de Acción */}
        <div className="flex flex-wrap items-center gap-2">
          {/* Selector de vistas */}
          <div className="inline-flex rounded-md border border-border bg-muted/40 p-0.5">
            {(
              [
                { id: "month", label: "Mes" },
                { id: "week", label: "Semana" },
                { id: "day", label: "Día" },
                { id: "agenda", label: "Agenda" },
              ] as const
            ).map((v) => (
              <button
                key={v.id}
                type="button"
                onClick={() => setView(v.id)}
                className={cn(
                  "rounded px-2.5 py-1 text-xs font-medium transition-colors",
                  view === v.id
                    ? "bg-background text-foreground shadow-xs font-semibold"
                    : "text-muted-foreground hover:text-foreground",
                )}
              >
                {v.label}
              </button>
            ))}
          </div>

          {onAddEvent && (
            <Button variant="primary" size="sm" onClick={onAddEvent}>
              + Nuevo evento
            </Button>
          )}
        </div>
      </div>

      {/* Barra de Filtros por Categoría (opcional) */}
      {categories && categories.length > 0 && (
        <div className="flex items-center gap-1.5 overflow-x-auto px-4 py-2 border-b border-border/60 bg-muted/10 text-xs">
          <span className="text-muted-foreground mr-1 text-[11px] uppercase tracking-wider font-medium">Filtrar:</span>
          <button
            type="button"
            onClick={() => setCategory("all")}
            className={cn(
              "rounded px-2 py-0.5 transition-colors font-medium",
              currentCategory === "all"
                ? "bg-foreground text-background"
                : "text-muted-foreground hover:bg-muted hover:text-foreground",
            )}
          >
            Todos
          </button>
          {categories.map((cat) => (
            <button
              key={cat.id}
              type="button"
              onClick={() => setCategory(cat.id)}
              className={cn(
                "flex items-center gap-1.5 rounded px-2 py-0.5 transition-colors font-medium",
                currentCategory === cat.id
                  ? "bg-muted text-foreground ring-1 ring-border"
                  : "text-muted-foreground hover:bg-muted/60 hover:text-foreground",
              )}
            >
              <span
                className={cn(
                  "h-1.5 w-1.5 rounded-full",
                  cat.variant === "primary" && "bg-primary",
                  cat.variant === "success" && "bg-success",
                  cat.variant === "danger" && "bg-danger",
                  cat.variant === "warning" && "bg-warning",
                  cat.variant === "info" && "bg-info",
                  cat.variant === "muted" && "bg-muted-foreground",
                )}
              />
              <span>{cat.label}</span>
            </button>
          ))}
        </div>
      )}

      {/* Renderizado de la Vista Activa */}
      <div className="w-full">
        {view === "month" && (
          <MonthView
            date={activeDate}
            events={filteredEvents}
            onEventClick={(ev) => {
              setActiveEvent(ev);
              onEventClick?.(ev);
            }}
            onSlotClick={(d) => onSlotClick?.(d)}
            locale={locale}
          />
        )}

        {view === "week" && (
          <WeekView
            date={activeDate}
            events={filteredEvents}
            onEventClick={(ev) => {
              setActiveEvent(ev);
              onEventClick?.(ev);
            }}
            onSlotClick={(d, h) => onSlotClick?.(d, h)}
            startHour={startHour}
            endHour={endHour}
            locale={locale}
          />
        )}

        {view === "day" && (
          <DayView
            date={activeDate}
            events={filteredEvents}
            onEventClick={(ev) => {
              setActiveEvent(ev);
              onEventClick?.(ev);
            }}
            onSlotClick={(d, h) => onSlotClick?.(d, h)}
            startHour={startHour}
            endHour={endHour}
            locale={locale}
          />
        )}

        {view === "agenda" && (
          <AgendaView
            events={filteredEvents}
            onEventClick={(ev) => {
              setActiveEvent(ev);
              onEventClick?.(ev);
            }}
            locale={locale}
          />
        )}
      </div>

      {/* Modal de Detalle */}
      <EventDetailsModal
        event={activeEvent}
        onClose={() => setActiveEvent(null)}
        locale={locale}
      />
    </div>
  );
}

Implementado en packages/ui/src/event-calendar.tsx usando la API nativa Intl.DateTimeFormat y micro-componentes de la librería (Button, Badge, ButtonGroup, Avatar).

Uso

import { useState } from "react";
import { EventCalendar, type CalendarEvent, type CalendarCategory, type CalendarView } from "@kenza-ui/ui";

const sampleCategories: CalendarCategory[] = [
  { id: "all", label: "Todas", variant: "primary" },
  { id: "design", label: "Diseño & UX", variant: "primary" },
  { id: "product", label: "Lanzamientos", variant: "success" },
  { id: "engineering", label: "Ingeniería", variant: "info" },
];

const sampleEvents: CalendarEvent[] = [
  {
    id: "evt-1",
    title: "Revisión de Sistema de Diseño Kenza",
    description: "Alineación de tokens tipográficos y componentes.",
    start: new Date(2026, 9, 20, 10, 0),
    end: new Date(2026, 9, 20, 11, 30),
    category: "design",
    variant: "primary",
    location: "Sala Editorial A",
    attendees: [
      { name: "Sofia Vega", fallback: "SV" },
      { name: "Mateo Ortiz", fallback: "MO" },
    ],
  },
];

export function MySchedule() {
  const [date, setDate] = useState(new Date());
  const [view, setView] = useState<CalendarView>("month");
  const [category, setCategory] = useState<string>("all");

  return (
    <EventCalendar
      events={sampleEvents}
      categories={sampleCategories}
      date={date}
      onDateChange={setDate}
      view={view}
      onViewChange={setView}
      selectedCategory={category}
      onSelectCategory={setCategory}
      onEventClick={(evt) => console.log("Evento seleccionado:", evt)}
      onAddEvent={() => console.log("Nuevo evento")}
    />
  );
}

API de EventCalendar

PropTipoDefault
eventsCalendarEvent[][]
view'month' | 'week' | 'day' | 'agenda''month'
onViewChange(view: CalendarView) => void—
dateDatenew Date()
onDateChange(date: Date) => void—
categoriesCalendarCategory[][]
selectedCategorystring—
onSelectCategory(category: string) => void—
localestring'es'
startHournumber8
endHournumber20
onEventClick(event: CalendarEvent) => void—
onSlotClick(date: Date, hour?: number) => void—
onAddEvent() => void—
classNamestring—

Estructura de CalendarEvent

PropTipoDefault
idstring—
titlestring—
startDate—
endDate—
allDaybooleanfalse
categorystring—
variant'primary' | 'success' | 'danger' | 'warning' | 'info' | 'muted''primary'
descriptionstring—
locationstring—
attendeesCalendarAttendee[]—