/* Calendar view — modern month grid */

function CalendarView({ tasks, onSelect, selectedId, onReschedule }) {
  const [anchorIso, setAnchorIso] = React.useState(TODAY.toISOString().slice(0, 7));
  const [dragOver, setDragOver] = React.useState(null);
  const [y, m] = anchorIso.split('-').map(Number);

  const first = new Date(y, m - 1, 1);
  const offset = (first.getDay() + 6) % 7;
  const start = new Date(first); start.setDate(first.getDate() - offset);

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

  const byDate = React.useMemo(() => {
    const map = new Map();
    tasks.forEach(t => {
      if (!t.dueDate) return;
      if (!map.has(t.dueDate)) map.set(t.dueDate, []);
      map.get(t.dueDate).push(t);
    });
    return map;
  }, [tasks]);

  const monthName = first.toLocaleDateString('en-GB', { month: 'long', year: 'numeric' });
  const totalDated = tasks.filter(t => t.dueDate).length;

  const nudge = (delta) => {
    const d = new Date(y, m - 1 + delta, 1);
    setAnchorIso(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`);
  };

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', background: 'rgb(var(--bg))', overflow: 'hidden', padding: '14px 20px 20px' }}>

      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '4px 4px 12px',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <button onClick={() => nudge(-1)} className="btn btn-secondary" style={{ padding: '5px 10px', fontSize: 12 }}>‹</button>
          <button onClick={() => setAnchorIso(TODAY.toISOString().slice(0,7))} className="btn btn-secondary" style={{ padding: '5px 12px', fontSize: 12 }}>Today</button>
          <button onClick={() => nudge(1)} className="btn btn-secondary" style={{ padding: '5px 10px', fontSize: 12 }}>›</button>
        </div>
        <h2 style={{ margin: 0, fontSize: 20, fontWeight: 700, letterSpacing: '-0.02em' }}>{monthName}</h2>
        <span style={{ fontSize: 12, color: 'rgb(var(--muted))', fontFamily: 'JetBrains Mono, monospace' }}>{totalDated} dated · {tasks.length} total</span>
      </div>

      <div style={{
        flex: 1,
        display: 'flex', flexDirection: 'column',
        background: 'rgb(var(--surface))',
        border: '1px solid rgb(var(--rule))',
        borderRadius: 12,
        overflow: 'hidden',
        boxShadow: 'var(--sh-sm)',
      }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', background: 'rgb(var(--paper-2) / 0.4)', borderBottom: '1px solid rgb(var(--rule))' }}>
          {['Mon','Tue','Wed','Thu','Fri','Sat','Sun'].map((d, i) => (
            <div key={d} style={{
              padding: '10px 14px', textAlign: 'left',
              fontSize: 11, fontWeight: 600, letterSpacing: '0.04em',
              color: i >= 5 ? 'rgb(var(--muted-2))' : 'rgb(var(--muted))',
              textTransform: 'uppercase',
            }}>{d}</div>
          ))}
        </div>

        <div style={{ flex: 1, display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gridAutoRows: '1fr', overflowY: 'auto' }}>
          {cells.map((d, i) => {
            const iso = d.toISOString().slice(0, 10);
            const cellTasks = byDate.get(iso) || [];
            const otherMonth = d.getMonth() !== m - 1;
            const isToday = iso === TODAY.toISOString().slice(0, 10);
            const isWeekend = d.getDay() === 0 || d.getDay() === 6;

            return (
              <div key={iso}
                onDragOver={e => { e.preventDefault(); setDragOver(iso); }}
                onDragLeave={() => setDragOver(d => d === iso ? null : d)}
                onDrop={e => {
                  e.preventDefault();
                  const id = parseInt(e.dataTransfer.getData('text/plain'), 10);
                  if (id && onReschedule) onReschedule(id, iso);
                  setDragOver(null);
                }}
                style={{
                borderRight: (i + 1) % 7 ? '1px solid rgb(var(--rule))' : 'none',
                borderBottom: '1px solid rgb(var(--rule))',
                padding: 8,
                minHeight: 110,
                background: dragOver === iso ? 'rgb(var(--accent-soft) / 0.6)' :
                            otherMonth ? 'rgb(var(--paper-2) / 0.35)' :
                            isWeekend ? 'rgb(var(--paper-2) / 0.18)' : 'transparent',
                display: 'flex', flexDirection: 'column', minWidth: 0,
                position: 'relative',
                transition: 'background-color .12s',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
                  <span style={{
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 12, fontVariantNumeric: 'tabular-nums', fontWeight: 600,
                    minWidth: 22, height: 22, padding: '0 6px',
                    color: otherMonth ? 'rgb(var(--rule-2))' :
                           isToday ? 'white' :
                           'rgb(var(--ink))',
                    background: isToday ? 'rgb(var(--accent))' : 'transparent',
                    borderRadius: 999,
                  }}>
                    {d.getDate()}
                  </span>
                  {cellTasks.length > 0 && (
                    <span className="num" style={{ fontSize: 10, color: 'rgb(var(--muted))', fontWeight: 500 }}>{cellTasks.length}</span>
                  )}
                </div>

                <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 3, overflow: 'hidden' }}>
                  {cellTasks.slice(0, 4).map(t => {
                    const st = statusById(t.statusId);
                    return (
                      <button key={t.id}
                        onClick={() => { onSelect(t.id); window.__openTaskModal?.(t.id); }}
                        draggable
                        onDragStart={e => { e.dataTransfer.setData('text/plain', String(t.id)); e.dataTransfer.effectAllowed = 'move'; e.stopPropagation(); }}
                        style={{
                          textAlign: 'left',
                          fontSize: 11, padding: '3px 7px',
                          background: st.colour + '14',
                          color: 'rgb(var(--ink))',
                          display: 'flex', alignItems: 'center', gap: 5,
                          overflow: 'hidden',
                          borderRadius: 6,
                          fontWeight: 500,
                          cursor: 'grab',
                        }}
                        onMouseEnter={e => e.currentTarget.style.background = st.colour + '24'}
                        onMouseLeave={e => e.currentTarget.style.background = st.colour + '14'}
                        title={t.title}>
                        <PriorityDot p={t.priority} />
                        <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{t.title}</span>
                      </button>
                    );
                  })}
                  {cellTasks.length > 4 && <span style={{ fontSize: 10.5, color: 'rgb(var(--muted))', paddingLeft: 6 }}>+{cellTasks.length - 4} more</span>}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.CalendarView = CalendarView;
