const MONTH_NAMES = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

function buildMonthGrid(year, month) {
  const first = new Date(year, month, 1);
  const startDow = first.getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const cells = [];
  for (let i = 0; i < startDow; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);
  return cells;
}

function SchedulerScreen({ onOpenEvent }) {
  const [mainEvents, setMainEvents] = React.useState(null);
  const now = new Date();
  const [cursor, setCursor] = React.useState({ year: now.getFullYear(), month: now.getMonth() });

  React.useEffect(() => { window.fetchMainEventsLive().then(setMainEvents); }, []);
  if (!mainEvents) return <div style={{ padding: 32, color: 'var(--text-muted)' }}>Loading…</div>;

  const items = mainEvents.flatMap((m) => m.subEvents.map((s) => {
    const dt = new Date(s.dateIso);
    return { ...s, mainId: m.id, y: dt.getFullYear(), m: dt.getMonth(), day: dt.getDate() };
  }));

  const cells = buildMonthGrid(cursor.year, cursor.month);
  const monthItems = items.filter((it) => it.y === cursor.year && it.m === cursor.month);

  function shift(delta) {
    setCursor((c) => {
      let m = c.month + delta, y = c.year;
      if (m < 0) { m = 11; y--; } if (m > 11) { m = 0; y++; }
      return { year: y, month: m };
    });
  }

  const categories = Array.from(new Set(items.map((it) => it.category).filter(Boolean)));

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20, flexWrap: 'wrap', gap: 12 }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
          <button onClick={() => shift(-1)} style={{ border: '1px solid var(--border-default)', background: 'white', borderRadius: 'var(--radius-md)', padding: '6px 12px', cursor: 'pointer' }}>‹</button>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-xl)', minWidth: 180, textAlign: 'center' }}>{MONTH_NAMES[cursor.month]} {cursor.year}</div>
          <button onClick={() => shift(1)} style={{ border: '1px solid var(--border-default)', background: 'white', borderRadius: 'var(--radius-md)', padding: '6px 12px', cursor: 'pointer' }}>›</button>
        </div>
        <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap' }}>
          {categories.map((c) => (
            <div key={c} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 'var(--text-xs)', color: 'var(--text-secondary)', textTransform: 'capitalize' }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: window.catColorMap[c] || 'var(--brand-primary)' }} />{c}
            </div>
          ))}
        </div>
      </div>

      <div style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', overflowX: 'auto' }}>
        <div style={{ minWidth: 700 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', borderBottom: '1px solid var(--border-default)' }}>
          {['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map((w) => (
            <div key={w} style={{ padding: '10px 12px', fontSize: 'var(--text-xs)', color: 'var(--text-muted)', textTransform: 'uppercase', textAlign: 'center' }}>{w}</div>
          ))}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)' }}>
          {cells.map((day, i) => {
            const dayItems = day ? monthItems.filter((it) => it.day === day) : [];
            return (
              <div key={i} style={{ minHeight: 96, borderRight: (i + 1) % 7 !== 0 ? '1px solid var(--border-default)' : 'none', borderBottom: '1px solid var(--border-default)', padding: 6 }}>
                {day && <div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-muted)', marginBottom: 6 }}>{day}</div>}
                {dayItems.map((it) => (
                  <div key={it.id} onClick={() => onOpenEvent(it.mainId)} title={it.title} style={{ background: 'color-mix(in srgb, ' + (window.catColorMap[it.category] || 'var(--brand-primary)') + ' 16%, white)', color: window.catColorMap[it.category] || 'var(--brand-primary)', borderRadius: 'var(--radius-sm)', padding: '3px 6px', fontSize: 'var(--text-xs)', marginBottom: 4, cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.title}</div>
                ))}
              </div>
            );
          })}
        </div>
        </div>
      </div>
    </div>
  );
}

window.SchedulerScreen = SchedulerScreen;
