const { useState } = React;
const T = window.ArbiterTokens;

const DAYS_IN_WEEK = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
const MONTH_NAMES = ['January','February','March','April','May','June','July','August','September','October','November','December'];

// Generate April 2026 calendar data
const CALENDAR_EVENTS = {
  '2026-04-21': [{ time: '10:00', label: 'Discovery cutoff', matter: 'Redstone v. Meridian', urgent: true }],
  '2026-04-22': [{ time: '09:00', label: 'Team standup', matter: 'Pacific Shipping', urgent: false }],
  '2026-04-23': [{ time: '14:00', label: 'Expert report due', matter: 'Thornton Estate', urgent: true }],
  '2026-04-25': [{ time: '09:30', label: 'Deposition — J. Harmon', matter: 'Pacific Shipping', urgent: false }, { time: '15:00', label: 'Client call', matter: 'Blackwell IP', urgent: false }],
  '2026-04-28': [{ time: '11:00', label: 'Motion to compel response', matter: 'Blackwell IP', urgent: false }],
  '2026-04-30': [{ time: '13:00', label: 'Partner review meeting', matter: 'Firm-wide', urgent: false }],
  '2026-05-02': [{ time: '08:30', label: 'Trial date', matter: 'Thornton Estate', urgent: true }],
  '2026-05-05': [{ time: '10:00', label: 'Mediation session', matter: 'Chen v. Atlas', urgent: false }],
  '2026-05-10': [{ time: '14:00', label: 'Settlement conference', matter: 'Marshall Employment', urgent: false }],
  '2026-05-14': [{ time: '17:00', label: 'Summary judgment deadline', matter: 'Redstone v. Meridian', urgent: true }],
};

const UPCOMING = [
  { date: 'Apr 21', time: '10:00 AM', label: 'Discovery cutoff', matter: 'Redstone v. Meridian', urgent: true },
  { date: 'Apr 23', time: '2:00 PM', label: 'Expert report due', matter: 'Thornton Estate', urgent: true },
  { date: 'Apr 25', time: '9:30 AM', label: 'Deposition — J. Harmon', matter: 'Pacific Shipping', urgent: false },
  { date: 'Apr 25', time: '3:00 PM', label: 'Client call', matter: 'Blackwell IP', urgent: false },
  { date: 'Apr 28', time: '11:00 AM', label: 'Motion to compel response', matter: 'Blackwell IP', urgent: false },
  { date: 'Apr 30', time: '1:00 PM', label: 'Partner review meeting', matter: 'Firm-wide', urgent: false },
  { date: 'May 02', time: '8:30 AM', label: 'Trial date', matter: 'Thornton Estate', urgent: true },
  { date: 'May 05', time: '10:00 AM', label: 'Mediation session', matter: 'Chen v. Atlas', urgent: false },
];

const calStyles = {
  container: { flex: 1, overflow: 'auto', background: T.color.bg.primary, padding: '20px' },
  header: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '20px' },
  title: { fontSize: T.font.size.xl, fontWeight: T.font.weight.bold, color: T.color.text.primary, letterSpacing: T.font.tracking.tight },
  grid: { display: 'grid', gridTemplateColumns: '1fr 320px', gap: '16px' },
  calCard: { background: T.color.bg.card, border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.lg, overflow: 'hidden' },
  monthNav: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 16px', borderBottom: `1px solid ${T.color.border.light}` },
  monthLabel: { fontSize: T.font.size.md, fontWeight: T.font.weight.semibold, color: T.color.text.primary },
  navBtn: { border: 'none', background: 'none', cursor: 'pointer', fontSize: '16px', color: T.color.text.secondary, padding: '4px 8px', borderRadius: T.radius.sm },
  dayGrid: { display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: '0' },
  dayHeader: { padding: '8px 4px', textAlign: 'center', fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps, borderBottom: `1px solid ${T.color.border.light}` },
  dayCell: {
    minHeight: '72px', padding: '4px 6px', borderBottom: `1px solid ${T.color.border.light}`,
    borderRight: `1px solid ${T.color.border.light}`, fontSize: T.font.size.xs, cursor: 'pointer',
    transition: 'background 0.1s', position: 'relative',
  },
  dayNum: { fontWeight: T.font.weight.medium, fontSize: T.font.size.sm, marginBottom: '3px' },
  dayEvent: {
    padding: '1px 4px', borderRadius: '3px', fontSize: '10px', fontWeight: T.font.weight.medium,
    marginBottom: '2px', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
    lineHeight: '16px',
  },
  today: { background: T.color.navy800, color: T.color.ivory100, width: '22px', height: '22px', borderRadius: '50%', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' },
  listItem: {
    padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`,
    display: 'flex', gap: '12px', alignItems: 'flex-start', fontSize: T.font.size.sm,
  },
};

function getDaysInMonth(year, month) {
  return new Date(year, month + 1, 0).getDate();
}
function getFirstDayOfMonth(year, month) {
  const d = new Date(year, month, 1).getDay();
  return d === 0 ? 6 : d - 1; // Monday = 0
}

function CalendarView() {
  const [month, setMonth] = useState(3); // April
  const [year, setYear] = useState(2026);
  const [selectedDate, setSelectedDate] = useState(null);
  const [hoveredCell, setHoveredCell] = useState(null);

  const daysInMonth = getDaysInMonth(year, month);
  const firstDay = getFirstDayOfMonth(year, month);
  const today = 20;
  const isCurrentMonth = month === 3 && year === 2026;

  const prevMonth = () => { if (month === 0) { setMonth(11); setYear(y=>y-1); } else setMonth(m=>m-1); };
  const nextMonth = () => { if (month === 11) { setMonth(0); setYear(y=>y+1); } else setMonth(m=>m+1); };

  const cells = [];
  for (let i = 0; i < firstDay; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);

  const getEvents = (day) => {
    if (!day) return [];
    const key = `${year}-${String(month+1).padStart(2,'0')}-${String(day).padStart(2,'0')}`;
    return CALENDAR_EVENTS[key] || [];
  };

  return (
    <div style={calStyles.container}>
      <div style={calStyles.header}>
        <div style={calStyles.title}>Calendar</div>
        <button style={{...window.sharedStyles.btn, ...window.sharedStyles.btnPrimary}}>+ Event</button>
      </div>
      <div style={calStyles.grid}>
        {/* Calendar grid */}
        <div style={calStyles.calCard}>
          <div style={calStyles.monthNav}>
            <button style={calStyles.navBtn} onClick={prevMonth}>‹</button>
            <span style={calStyles.monthLabel}>{MONTH_NAMES[month]} {year}</span>
            <button style={calStyles.navBtn} onClick={nextMonth}>›</button>
          </div>
          <div style={calStyles.dayGrid}>
            {DAYS_IN_WEEK.map(d => <div key={d} style={calStyles.dayHeader}>{d}</div>)}
            {cells.map((day, i) => {
              const events = getEvents(day);
              const isToday = isCurrentMonth && day === today;
              return (
                <div key={i} style={{
                  ...calStyles.dayCell,
                  background: hoveredCell === i && day ? T.color.bg.hover : day ? 'transparent' : T.color.bg.secondary,
                  borderRight: (i + 1) % 7 === 0 ? 'none' : calStyles.dayCell.borderRight,
                  opacity: day ? 1 : 0.3,
                }}
                  onMouseEnter={() => setHoveredCell(i)}
                  onMouseLeave={() => setHoveredCell(null)}
                  onClick={() => day && setSelectedDate(day)}
                >
                  {day && (
                    <>
                      <div style={calStyles.dayNum}>
                        {isToday ? <span style={calStyles.today}>{day}</span> : day}
                      </div>
                      {events.map((ev, j) => (
                        <div key={j} style={{
                          ...calStyles.dayEvent,
                          background: ev.urgent ? T.color.status.criticalBg : T.color.accent.blueBg,
                          color: ev.urgent ? T.color.status.critical : T.color.accent.blue,
                        }}>{ev.label}</div>
                      ))}
                    </>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* Upcoming list */}
        <div>
          <div style={calStyles.calCard}>
            <div style={{ padding: '12px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontWeight: T.font.weight.semibold, fontSize: T.font.size.sm }}>Upcoming Events</div>
            {UPCOMING.map((ev, i) => (
              <div key={i} style={calStyles.listItem}>
                <div style={{ minWidth: '52px' }}>
                  <div style={{ fontSize: T.font.size.xs, fontWeight: T.font.weight.semibold, color: ev.urgent ? T.color.status.critical : T.color.text.tertiary, fontFamily: T.font.mono }}>{ev.date}</div>
                  <div style={{ fontSize: '10px', color: T.color.text.tertiary, fontFamily: T.font.mono }}>{ev.time}</div>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: T.font.weight.medium, color: T.color.text.primary }}>{ev.label}</div>
                  <div style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary, marginTop: '1px' }}>{ev.matter}</div>
                </div>
                {ev.urgent && <span style={{ fontSize: '8px', color: T.color.status.critical, marginTop: '4px' }}>●</span>}
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

window.CalendarView = CalendarView;
