// Calendar grid component. month view with event dots + hover quicklook

const { useState, useEffect, useRef, useMemo } = React;

function EventList({ events, onSelectEvent, t }) {
  const [monthDate, setMonthDate] = useState(new Date(2026, 3, 1));
  const year = monthDate.getFullYear();
  const month = monthDate.getMonth();
  const monthLabel = monthDate.toLocaleDateString('en-US', { month: 'long', year: 'numeric' }).toUpperCase();
  const prevMonth = () => setMonthDate(new Date(year, month - 1, 1));
  const nextMonth = () => setMonthDate(new Date(year, month + 1, 1));

  const monthEvents = events.filter(ev => {
    const d = new Date(ev.date + 'T00:00:00');
    return d.getFullYear() === year && d.getMonth() === month;
  });
  const sorted = [...monthEvents].sort((a, b) => (a.date + a.time).localeCompare(b.date + b.time));
  // Group by date
  const groups = {};
  sorted.forEach(ev => { if (!groups[ev.date]) groups[ev.date] = []; groups[ev.date].push(ev); });
  const today = '2026-04-20';
  return (
    <div style={{ padding: '20px 16px 60px' }}>
      <div style={{
        fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
        letterSpacing: '0.25em', color: t.dim, marginBottom: 8,
      }}>OPERATIONS CALENDAR</div>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: 8, gap: 10,
      }}>
        <button onClick={prevMonth} style={{
          width: 40, height: 40, background: 'transparent',
          border: `1px solid ${t.lineStrong}`, color: t.fg, cursor: 'pointer',
          fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 14,
          flexShrink: 0,
        }}>◀</button>
        <h1 style={{
          fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 26,
          color: t.fg, margin: 0, letterSpacing: '0.02em', lineHeight: 1,
          textAlign: 'center', flex: 1,
        }}>{monthLabel}</h1>
        <button onClick={nextMonth} style={{
          width: 40, height: 40, background: 'transparent',
          border: `1px solid ${t.lineStrong}`, color: t.fg, cursor: 'pointer',
          fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 14,
          flexShrink: 0,
        }}>▶</button>
      </div>
      <div style={{
        fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
        letterSpacing: '0.2em', color: t.dim, marginBottom: 20, textAlign: 'center',
      }}>{monthEvents.length} {monthEvents.length === 1 ? 'EVENT' : 'EVENTS'}</div>
      {monthEvents.length === 0 ? (
        <div style={{
          padding: '40px 20px', textAlign: 'center',
          border: `1px dashed ${t.line}`, background: t.cellBg,
          fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 13,
          color: t.dim, letterSpacing: '0.1em',
        }}>NO EVENTS SCHEDULED THIS MONTH</div>
      ) : Object.keys(groups).map(date => {
        const dateObj = new Date(date + 'T00:00:00');
        const dayStr = dateObj.toLocaleDateString('en-US', { weekday: 'long' }).toUpperCase();
        const dayNum = dateObj.getDate();
        const monthStr = dateObj.toLocaleDateString('en-US', { month: 'short' }).toUpperCase();
        const isToday = date === today;
        return (
          <div key={date} style={{ marginBottom: 24 }}>
            <div style={{
              display: 'flex', alignItems: 'baseline', gap: 12,
              paddingBottom: 10, borderBottom: `1px solid ${t.line}`, marginBottom: 10,
            }}>
              <div style={{
                fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 32,
                color: isToday ? t.brass : t.fg, lineHeight: 1,
              }}>{String(dayNum).padStart(2, '0')}</div>
              <div style={{ flex: 1 }}>
                <div style={{
                  fontFamily: 'Barlow, sans-serif', fontWeight: 600, fontSize: 11,
                  letterSpacing: '0.2em', color: isToday ? t.brass : t.fg,
                }}>{dayStr}</div>
                <div style={{
                  fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
                  letterSpacing: '0.2em', color: t.dim,
                }}>{monthStr} 2026{isToday ? ' · NOW' : ''}</div>
              </div>
            </div>
            {groups[date].map(ev => (
              <div key={ev.id} onClick={() => onSelectEvent(ev)} style={{
                background: t.cellBg, border: `1px solid ${t.line}`,
                borderLeft: `3px solid ${t.brass}`,
                padding: '14px 14px', marginBottom: 8, cursor: 'pointer',
              }}>
                <div style={{
                  display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
                  gap: 8, marginBottom: 6,
                }}>
                  <div style={{
                    fontFamily: 'Barlow, sans-serif', fontWeight: 600, fontSize: 10,
                    letterSpacing: '0.2em', color: t.brass,
                  }}>{ev.time}{ev.endTime ? `–${ev.endTime}` : ''}</div>
                  <div style={{
                    fontFamily: 'Barlow, sans-serif', fontWeight: 600, fontSize: 9,
                    letterSpacing: '0.2em', color: t.brass,
                    border: `1px solid ${t.brass}`, padding: '2px 6px',
                  }}>{ev.tag}</div>
                </div>
                <div style={{
                  fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 17,
                  color: t.fg, letterSpacing: '0.02em', lineHeight: 1.15,
                  marginBottom: 6,
                }}>{ev.title}</div>
                <div style={{
                  fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 11,
                  letterSpacing: '0.1em', color: t.dim, textTransform: 'uppercase',
                  marginBottom: 8,
                }}>◉ {ev.location}</div>
                <div style={{
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  paddingTop: 8, borderTop: `1px solid ${t.line}`,
                }}>
                  <div style={{
                    fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
                    letterSpacing: '0.15em', color: t.dim,
                  }}>{ev.capacity > 0 ? `${ev.signed} / ${ev.capacity} SIGNED` : `${ev.signed} SIGNED · OPEN`}</div>
                  <div style={{
                    fontFamily: 'Barlow, sans-serif', fontWeight: 600, fontSize: 10,
                    letterSpacing: '0.2em', color: t.brass,
                  }}>VIEW →</div>
                </div>
              </div>
            ))}
          </div>
        );
      })}
    </div>
  );
}

function Calendar({ events, onSelectEvent, t, density, phoneMode }) {
  if (phoneMode) {
    return <EventList events={events} onSelectEvent={onSelectEvent} t={t} />;
  }
  const [monthDate, setMonthDate] = useState(new Date(2026, 3, 1));
  const [hoverEvent, setHoverEvent] = useState(null);
  const [hoverPos, setHoverPos] = useState({ x: 0, y: 0 });
  const gridRef = useRef(null);

  const year = monthDate.getFullYear();
  const month = monthDate.getMonth();
  const monthLabel = monthDate.toLocaleDateString('en-US', { month: 'long', year: 'numeric' }).toUpperCase();

  const firstDow = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const prevDaysInMonth = new Date(year, month, 0).getDate();

  const cells = [];
  for (let i = 0; i < firstDow; i++) {
    cells.push({ day: prevDaysInMonth - firstDow + 1 + i, inMonth: false, date: null });
  }
  for (let d = 1; d <= daysInMonth; d++) {
    const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
    cells.push({ day: d, inMonth: true, date: dateStr });
  }
  while (cells.length < 42) {
    cells.push({ day: cells.length - firstDow - daysInMonth + 1, inMonth: false, date: null });
  }

  const eventsByDate = useMemo(() => {
    const map = {};
    events.forEach(e => { if (!map[e.date]) map[e.date] = []; map[e.date].push(e); });
    return map;
  }, [events]);

  const today = '2026-04-20';
  const rowH = density === 'compact' ? 84 : 112;

  const handleMouseEnter = (e, event, cellEl) => {
    const rect = cellEl.getBoundingClientRect();
    const gridRect = gridRef.current.getBoundingClientRect();
    setHoverEvent(event);
    setHoverPos({ x: rect.right - gridRect.left + 12, y: rect.top - gridRect.top });
  };

  const prevMonth = () => setMonthDate(new Date(year, month - 1, 1));
  const nextMonth = () => setMonthDate(new Date(year, month + 1, 1));

  return (
    <div style={{ position: 'relative' }} ref={gridRef}>
      <div style={{
        display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
        paddingBottom: 20, borderBottom: `1px solid ${t.line}`, marginBottom: 24,
      }}>
        <div>
          <div style={{
            fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 11,
            letterSpacing: '0.25em', color: t.dim, marginBottom: 8,
          }}>OPERATIONS CALENDAR / 04</div>
          <h1 style={{
            fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 56,
            color: t.fg, margin: 0, letterSpacing: '0.02em', lineHeight: 1,
          }}>{monthLabel}</h1>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <NavBtn onClick={prevMonth} t={t}>◀ PREV</NavBtn>
          <NavBtn onClick={() => setMonthDate(new Date(2026, 3, 1))} t={t}>TODAY</NavBtn>
          <NavBtn onClick={nextMonth} t={t}>NEXT ▶</NavBtn>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 1, marginBottom: 1 }}>
        {['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'].map(d => (
          <div key={d} style={{
            fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
            letterSpacing: '0.25em', color: t.dim, padding: '10px 12px',
          }}>{d}</div>
        ))}
      </div>

      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 1,
        background: t.line, border: `1px solid ${t.line}`,
      }}>
        {cells.map((cell, i) => {
          const dayEvents = cell.date ? (eventsByDate[cell.date] || []) : [];
          const isToday = cell.date === today;
          return (
            <div key={i} style={{
              height: rowH, background: t.cellBg, padding: '8px 10px',
              position: 'relative', opacity: cell.inMonth ? 1 : 0.3,
              display: 'flex', flexDirection: 'column',
            }}>
              <div style={{
                display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
                marginBottom: 6,
              }}>
                <span style={{
                  fontFamily: 'Barlow, sans-serif', fontWeight: isToday ? 600 : 300,
                  fontSize: 13, color: isToday ? t.brass : t.fg, letterSpacing: '0.05em',
                }}>{String(cell.day).padStart(2, '0')}</span>
                {isToday && (
                  <span style={{
                    fontFamily: 'Barlow, sans-serif', fontSize: 8, fontWeight: 600,
                    letterSpacing: '0.25em', color: t.brass,
                    border: `1px solid ${t.brass}`, padding: '1px 4px',
                  }}>NOW</span>
                )}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 2, flex: 1 }}>
                {dayEvents.map(ev => (
                  <EventPill
                    key={ev.id} event={ev} t={t}
                    onMouseEnter={(e) => handleMouseEnter(e, ev, e.currentTarget.parentElement.parentElement)}
                    onMouseLeave={() => setHoverEvent(null)}
                    onClick={() => onSelectEvent(ev)}
                  />
                ))}
              </div>
            </div>
          );
        })}
      </div>

      {hoverEvent && <Quicklook event={hoverEvent} pos={hoverPos} t={t} />}
    </div>
  );
}

function NavBtn({ children, onClick, t }) {
  const [hover, setHover] = useState(false);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 11,
        letterSpacing: '0.2em', padding: '10px 18px', background: 'transparent',
        border: `1px solid ${hover ? t.brass : t.lineStrong}`,
        color: hover ? t.brass : t.fg, cursor: 'pointer', transition: 'all 0.15s',
      }}
    >{children}</button>
  );
}

function EventPill({ event, t, onMouseEnter, onMouseLeave, onClick }) {
  const [hover, setHover] = useState(false);
  return (
    <div
      onMouseEnter={(e) => { setHover(true); onMouseEnter(e); }}
      onMouseLeave={() => { setHover(false); onMouseLeave(); }}
      onClick={onClick}
      style={{
        padding: '3px 6px',
        background: hover ? t.brass : 'transparent',
        borderLeft: `2px solid ${t.brass}`,
        cursor: 'pointer', transition: 'background 0.1s', overflow: 'hidden',
      }}
    >
      <div style={{
        fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 10,
        letterSpacing: '0.08em',
        color: hover ? '#0F1114' : t.fg,
        whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', lineHeight: 1.2,
      }}>{event.time} · {event.title}</div>
      <div style={{
        fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 9,
        color: hover ? 'rgba(15,17,20,0.7)' : t.dim,
        letterSpacing: '0.08em', marginTop: 1,
        whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
        textTransform: 'uppercase',
      }}>◉ {event.location}</div>
    </div>
  );
}

function Quicklook({ event, pos, t }) {
  const dateObj = new Date(event.date + 'T00:00:00');
  const dateStr = dateObj.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' }).toUpperCase();

  return (
    <div style={{
      position: 'absolute', left: Math.min(pos.x, 800), top: pos.y, width: 320,
      background: t.bg, border: `1px solid rgba(199,150,62,0.45)`,
      boxShadow: t.shadow, pointerEvents: 'none', zIndex: 100,
      animation: 'quickIn 0.12s ease-out',
    }}>
      <div style={{
        height: event.image ? 180 : 120, position: 'relative', overflow: 'hidden',
        background: event.image ? '#000' : `repeating-linear-gradient(135deg, ${t.stripeA} 0 8px, ${t.stripeB} 8px 16px)`,
        borderBottom: `1px solid ${t.line}`,
      }}>
        {event.image ? (
          <img src={event.image} alt={event.title} style={{
            width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center top', display: 'block',
          }} />
        ) : (
          <div style={{
            position: 'absolute', inset: 0, display: 'flex',
            alignItems: 'center', justifyContent: 'center',
          }}>
            <span style={{
              fontFamily: 'ui-monospace, monospace', fontSize: 10,
              color: t.dimmer, letterSpacing: '0.15em',
            }}>[ EVENT IMAGE / {event.type.toUpperCase()} ]</span>
          </div>
        )}
        <div style={{
          position: 'absolute', top: 10, left: 10,
          fontFamily: 'Barlow, sans-serif', fontWeight: 600, fontSize: 9,
          letterSpacing: '0.25em', color: '#0F1114',
          background: t.brass, padding: '3px 8px',
        }}>{event.tag}</div>
      </div>

      <div style={{ padding: '14px 16px 16px' }}>
        <div style={{
          fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
          letterSpacing: '0.25em', color: t.brass, marginBottom: 8,
        }}>{dateStr} · {event.time}–{event.endTime}</div>
        <h3 style={{
          fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 22,
          color: t.fg, margin: '0 0 10px', letterSpacing: '0.02em', lineHeight: 1.1,
        }}>{event.title}</h3>
        <div style={{
          fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 11,
          letterSpacing: '0.15em', color: t.dim,
          marginBottom: 10, textTransform: 'uppercase',
        }}>◉ {event.location}</div>
        <p style={{
          fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 13,
          color: t.fg, opacity: 0.85, margin: 0, lineHeight: 1.5,
        }}>{event.brief}</p>
        <div style={{
          marginTop: 14, paddingTop: 10, borderTop: `1px solid ${t.line}`,
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        }}>
          <div style={{
            fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
            letterSpacing: '0.2em', color: t.dim,
          }}>{event.capacity > 0 ? `${event.signed} / ${event.capacity} SIGNED` : `${event.signed} SIGNED · OPEN`}</div>
          <div style={{
            fontFamily: 'Barlow, sans-serif', fontWeight: 600, fontSize: 10,
            letterSpacing: '0.25em', color: t.brass,
          }}>CLICK TO SIGN UP →</div>
        </div>
      </div>
    </div>
  );
}

window.Calendar = Calendar;
