// calendar.jsx — Month view for MamaFlow

function Calendar({ tasks, family, theme, density, tab, setTab, onToggle, onTaskClick }) {
  const [cursor, setCursor] = React.useState(() => {
    const d = new Date(); d.setDate(1); return d;
  });
  const [selected, setSelected] = React.useState(todayISO());

  const year = cursor.getFullYear();
  const month = cursor.getMonth();
  const monthLabel = `${MON[month].charAt(0) + MON[month].slice(1).toLowerCase()} ${year}`;

  const firstDow = new Date(year, month, 1).getDay(); // 0=Sun
  // We want week starts on Monday (Spanish convention)
  const mondayOffset = (firstDow + 6) % 7;
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const cells = [];
  for (let i = 0; i < mondayOffset; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);
  while (cells.length % 7 !== 0) cells.push(null);
  while (cells.length < 42) cells.push(null);

  const isoFor = (d) => `${year}-${String(month+1).padStart(2,'0')}-${String(d).padStart(2,'0')}`;
  const tasksOn = (d) => tasks.filter(t => t.date === isoFor(d));

  const selectedTasks = tasks.filter(t => t.date === selected);
  const dowLabels = ['L','M','M','J','V','S','D'];

  const prevMonth = () => { const d = new Date(cursor); d.setMonth(d.getMonth() - 1); setCursor(d); };
  const nextMonth = () => { const d = new Date(cursor); d.setMonth(d.getMonth() + 1); setCursor(d); };

  // Month stats for header subline
  const monthTasks = tasks.filter(t => {
    const [yy, mm] = t.date.split('-').map(Number);
    return yy === year && mm === month + 1;
  });
  const monthPending = monthTasks.filter(t => !t.done).length;
  const monthDone = monthTasks.filter(t => t.done).length;

  return (
    <div style={{ paddingBottom: 140 }}>
      {/* Month header — mismo formato que Home y Tú */}
      <div style={{
        background: headerGradient(theme, false), color: 'white',
        padding: '64px 18px 18px',
      }}>
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
          marginBottom: 12,
        }}>
          <div style={{
            fontSize: 11, fontWeight: 700, letterSpacing: 1.3,
            color: 'rgba(255,255,255,0.65)', marginTop: 4,
          }}>VISTA MENSUAL</div>
          <div style={{ display: 'flex', gap: 6 }}>
            <button onClick={prevMonth} style={navBtn}>‹</button>
            <button onClick={() => { setCursor(new Date(new Date().getFullYear(), new Date().getMonth(), 1)); setSelected(todayISO()); }} style={{ ...navBtn, fontSize: 11, padding: '0 10px', width: 'auto', minWidth: 32 }}>Hoy</button>
            <button onClick={nextMonth} style={navBtn}>›</button>
          </div>
        </div>
        <div style={{
          fontSize: 24, fontWeight: 700, letterSpacing: -0.4,
          lineHeight: 1.15, marginBottom: 4,
        }}>{monthLabel}</div>
        <div style={{
          fontSize: 13, color: 'rgba(255,255,255,0.78)', marginBottom: 16,
        }}>
          {monthPending} {monthPending === 1 ? 'tarea pendiente' : 'tareas pendientes'} · {monthDone} {monthDone === 1 ? 'hecha' : 'hechas'}
        </div>
      </div>

      {/* View switcher */}
      <div style={{ padding: '14px 18px 0', display: 'flex', alignItems: 'center', gap: 10, background: theme.surface }}>
        <ViewSwitcher value={tab} onChange={setTab} theme={theme} />
      </div>



      {/* Day-of-week strip */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)',
        padding: '12px 12px 6px',
        background: theme.surface,
        borderBottom: `1px solid ${theme.borderSoft}`,
      }}>
        {dowLabels.map((l, i) => (
          <div key={i} style={{
            textAlign: 'center', fontSize: 10.5, fontWeight: 700,
            color: theme.textSoft, letterSpacing: 0.6,
          }}>{l}</div>
        ))}
      </div>

      {/* Calendar grid */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)',
        background: theme.surface,
        padding: '4px 12px 12px',
      }}>
        {cells.map((d, i) => {
          if (d == null) return <div key={i} style={{ height: 46 }} />;
          const iso = isoFor(d);
          const isToday = iso === todayISO();
          const isSelected = iso === selected;
          const items = tasksOn(d);
          const pillars = [...new Set(items.map(t => t.pillar))].slice(0, 4);
          return (
            <button key={i} onClick={() => setSelected(iso)}
              style={{
                appearance: 'none', cursor: 'pointer',
                height: 46, margin: 1, padding: 0,
                border: 'none', background: 'transparent',
                display: 'flex', flexDirection: 'column',
                alignItems: 'center', justifyContent: 'flex-start',
                gap: 3, paddingTop: 5,
                fontFamily: 'inherit',
                borderRadius: 10,
                ...(isSelected ? { background: theme.primarySoft, border: `1px solid ${theme.primaryBorder}` } : {}),
              }}>
              <div style={{
                width: 24, height: 24, borderRadius: '50%',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 12.5, fontWeight: isToday ? 700 : 500,
                background: isToday ? theme.primary : 'transparent',
                color: isToday ? 'white' : (isSelected ? theme.primary : theme.text),
              }}>{d}</div>
              <div style={{ display: 'flex', gap: 2 }}>
                {pillars.map(pid => (
                  <span key={pid} style={{
                    width: 4, height: 4, borderRadius: '50%',
                    background: PILLARS[pid].text,
                  }}/>
                ))}
              </div>
            </button>
          );
        })}
      </div>

      {/* Selected day list */}
      <div style={{ padding: '16px 0 0' }}>
        <div style={{
          padding: '0 18px', marginBottom: 10,
          display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
        }}>
          <div style={{
            fontSize: 13.5, fontWeight: 700, color: theme.text, letterSpacing: -0.1,
          }}>{relativeDay(selected)} · {fmtDateShort(selected)}</div>
          <div style={{ fontSize: 11, color: theme.textSoft, fontWeight: 500 }}>
            {selectedTasks.length} {selectedTasks.length === 1 ? 'tarea' : 'tareas'}
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: DENSITY[density].gap, padding: '0 18px' }}>
          {selectedTasks.length === 0 ? (
            <div style={{
              padding: '18px', textAlign: 'center',
              color: theme.textSoft, fontSize: 12.5,
              background: theme.surface, borderRadius: 12,
              border: `1px dashed ${theme.border}`,
            }}>Sin tareas este día</div>
          ) : selectedTasks.map(t => (
            <TaskCard key={t.id} task={t} family={family} theme={theme}
              density={density} onToggle={onToggle} onClick={() => onTaskClick(t)} />
          ))}
        </div>
      </div>

      {/* Pillar legend */}
      <div style={{
        padding: '24px 18px 0',
      }}>
        <div style={{
          fontSize: 10.5, fontWeight: 700, letterSpacing: 1.2,
          color: theme.textSoft, textTransform: 'uppercase', marginBottom: 8,
        }}>Leyenda</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {Object.keys(PILLARS).map(pid => (
            <div key={pid} style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              fontSize: 11, color: theme.textSoft, fontWeight: 500,
              background: theme.surface, padding: '4px 9px',
              border: `1px solid ${theme.border}`, borderRadius: 999,
            }}>
              <span style={{ width: 6, height: 6, borderRadius: '50%', background: PILLARS[pid].text }} />
              {PILLARS[pid].label}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

const navBtn = {
  appearance: 'none', cursor: 'pointer',
  background: 'rgba(255,255,255,0.18)', border: 'none',
  width: 32, height: 32, borderRadius: 10,
  color: 'white', fontSize: 18, fontWeight: 600,
  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
  fontFamily: 'inherit', lineHeight: 1,
};

Object.assign(window, { Calendar });
