// Calendar view — month grid showing scheduled/published integrations.
const { useState: useStateC } = React;

function CalendarView({ creators, onEventClick }) {
  // Default to current month, but for demo use May 2026
  const [cursor, setCursor] = useStateC(new Date(2026, 4, 1));
  const year = cursor.getFullYear();
  const month = cursor.getMonth();

  // Build month grid: 6 rows of 7 = 42 cells, starting on Monday
  const firstDay = new Date(year, month, 1);
  const startOffset = (firstDay.getDay() + 6) % 7; // Monday=0
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const daysInPrev = new Date(year, month, 0).getDate();
  const cells = [];
  for (let i = 0; i < 42; i++) {
    const dayNum = i - startOffset + 1;
    if (dayNum < 1) {
      cells.push({ date: new Date(year, month - 1, daysInPrev + dayNum), muted: true });
    } else if (dayNum > daysInMonth) {
      cells.push({ date: new Date(year, month + 1, dayNum - daysInMonth), muted: true });
    } else {
      cells.push({ date: new Date(year, month, dayNum), muted: false });
    }
  }

  // Events per day key
  const events = {};
  creators.forEach(c => {
    const i = c.integration;
    if (!i) return;
    const d = i.publishedAt || i.scheduledAt;
    if (!d) return;
    const key = `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
    (events[key] = events[key] || []).push({ creator: c, type: i.publishedAt ? "published" : "scheduled" });
  });

  const today = new Date(2026, 4, 25); // pinned demo "today"
  const monthName = cursor.toLocaleDateString("en-US", { month: "long", year: "numeric" });

  return (
    <div>
      <div className="between" style={{ marginBottom: 12 }}>
        <div className="row gap-8">
          <button className="btn sm" onClick={() => setCursor(new Date(year, month - 1, 1))}>
            <IconChevronLeft size={14} />
          </button>
          <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700, textTransform: "capitalize" }}>{monthName}</h3>
          <button className="btn sm" onClick={() => setCursor(new Date(year, month + 1, 1))}>
            <IconChevron size={14} />
          </button>
          <button className="btn sm ghost" onClick={() => setCursor(new Date(2026, 4, 1))}>Today</button>
        </div>
        <div className="row gap-12 small muted">
          <span><span style={{ display: "inline-block", width: 10, height: 10, borderRadius: 3, background: "var(--accent-500)", verticalAlign: "-1px", marginRight: 5 }} />Published</span>
          <span><span style={{ display: "inline-block", width: 10, height: 10, borderRadius: 3, background: "var(--warning)", verticalAlign: "-1px", marginRight: 5 }} />Scheduled</span>
        </div>
      </div>

      <div className="calendar-grid">
        {["Mon","Tue","Wed","Thu","Fri","Sat","Sun"].map(d => (
          <div className="cal-head" key={d}>{d}</div>
        ))}
        {cells.map((cell, idx) => {
          const key = `${cell.date.getFullYear()}-${cell.date.getMonth()}-${cell.date.getDate()}`;
          const dayEvents = events[key] || [];
          const isToday = cell.date.toDateString() === today.toDateString();
          return (
            <div key={idx} className={`cal-cell ${cell.muted ? "muted" : ""} ${isToday ? "today" : ""}`}>
              <div className="daynum">{cell.date.getDate()}</div>
              {dayEvents.slice(0, 3).map((e, i) => (
                <div
                  className="cal-event"
                  key={i}
                  onClick={() => onEventClick(e.creator)}
                  style={e.type === "scheduled" ? {
                    background: "rgba(217, 119, 6, 0.12)",
                    color: "var(--warning)",
                  } : {}}
                >
                  <PlatformBadge platform={e.creator.platform} size={12} />
                  <span style={{ overflow: "hidden", textOverflow: "ellipsis" }}>{e.creator.name}</span>
                </div>
              ))}
              {dayEvents.length > 3 && (
                <div className="small muted" style={{ fontSize: 10 }}>+{dayEvents.length - 3} more</div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { CalendarView });
