// Calendar view: month grid with task indicators + day detail panel

function CalendarView({ items, openForm, onStatusChange, onEdit }) {
  const [cursor, setCursor] = React.useState(new Date(TODAY.getFullYear(), TODAY.getMonth(), 1));
  const [selected, setSelected] = React.useState(TODAY);

  const month = cursor.getMonth(); const year = cursor.getFullYear();
  const first = new Date(year, month, 1);
  const last = new Date(year, month + 1, 0);
  // Start grid on Monday
  const startWeekday = (first.getDay() + 6) % 7; // 0 = Mon
  const totalDays = last.getDate();
  const cells = [];
  for (let i = 0; i < startWeekday; i++) cells.push({ outside: true, date: addDays(first, i - startWeekday) });
  for (let d = 1; d <= totalDays; d++) cells.push({ outside: false, date: new Date(year, month, d) });
  while (cells.length % 7 !== 0) cells.push({ outside: true, date: addDays(last, cells.length - startWeekday - totalDays + 1) });

  const dayItems = itemsOnDate(items, selected);

  return (
    <div className="col gap-5 view-pad" style={{ maxWidth: 1280, margin: "0 auto" }}>
      <SectionHeading
        eyebrow="Vue calendrier"
        title={
          <span>
            {MONTHS[month].charAt(0).toUpperCase() + MONTHS[month].slice(1)}{" "}
            <span style={{ color: "var(--ink-3)" }}>{year}</span>
          </span>
        }
        action={
          <div className="row gap-2">
            <IconButton icon="back" label="Mois précédent" onClick={() => setCursor(new Date(year, month - 1, 1))} />
            <Button variant="soft" onClick={() => { setCursor(new Date(TODAY.getFullYear(), TODAY.getMonth(), 1)); setSelected(TODAY); }}>Aujourd'hui</Button>
            <IconButton icon="chev" label="Mois suivant" onClick={() => setCursor(new Date(year, month + 1, 1))} />
          </div>
        }
      />

      <div className="grid-2col" style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 20 }}>
        <Card padding={0}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", borderBottom: "1px solid var(--line)" }}>
            {["lun.","mar.","mer.","jeu.","ven.","sam.","dim."].map(d => (
              <div key={d} className="tiny cal-header-cell" style={{ padding: "12px 14px", textAlign: "left" }}>{d}</div>
            ))}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)" }}>
            {cells.map((cell, i) => {
              const its = itemsOnDate(items, cell.date);
              const isToday = sameDay(cell.date, TODAY);
              const isSelected = sameDay(cell.date, selected);
              return (
                <button
                  key={i}
                  className="cal-cell"
                  onClick={() => setSelected(cell.date)}
                  style={{
                    minHeight: 110, padding: 10, textAlign: "left",
                    borderRight: (i + 1) % 7 === 0 ? "none" : "1px solid var(--line)",
                    borderBottom: i >= cells.length - 7 ? "none" : "1px solid var(--line)",
                    background: isSelected
                      ? "var(--terracotta-tint)"
                      : (cell.outside ? "var(--bg-2)" : "transparent"),
                    color: cell.outside ? "var(--ink-4)" : "var(--ink)",
                    cursor: "pointer", position: "relative",
                    transition: "background .15s ease",
                  }}
                  onMouseEnter={(e) => { if (!isSelected && !cell.outside) e.currentTarget.style.background = "var(--bg-2)"; }}
                  onMouseLeave={(e) => { if (!isSelected) e.currentTarget.style.background = cell.outside ? "var(--bg-2)" : "transparent"; }}
                >
                  <div className="row gap-2" style={{ justifyContent: "space-between", alignItems: "flex-start" }}>
                    <div style={{
                      width: 28, height: 28, borderRadius: 999,
                      display: "flex", alignItems: "center", justifyContent: "center",
                      fontFamily: "var(--font-display)", fontSize: 17,
                      background: isToday ? "var(--terracotta)" : "transparent",
                      color: isToday ? "#FFF8F0" : "inherit",
                      fontWeight: isToday ? 500 : 400,
                    }}>{cell.date.getDate()}</div>
                    {its.length > 0 && (
                      <div className="tiny" style={{ color: cell.outside ? "var(--ink-4)" : "var(--ink-3)" }}>{its.length}</div>
                    )}
                  </div>
                  <div className="col gap-1 cal-chips" style={{ marginTop: 6 }}>
                    {its.slice(0, 3).map((it, j) => {
                      const isTask = it.kind === "task";
                      const c = isTask ? STATES[statusOn(it, cell.date)].color : KINDS[it.kind].color;
                      const bg = isTask ? STATES[statusOn(it, cell.date)].bg : KINDS[it.kind].bg;
                      return (
                        <div key={j} className="truncate" style={{
                          fontSize: 11, lineHeight: 1.2,
                          padding: "2px 6px", borderRadius: 4,
                          background: bg, color: c,
                          borderLeft: `2px solid ${c}`,
                        }}>{it.title}</div>
                      );
                    })}
                    {its.length > 3 && <div className="tiny" style={{ color: "var(--ink-3)" }}>+ {its.length - 3} autres</div>}
                  </div>
                </button>
              );
            })}
          </div>
        </Card>

        {/* Day detail */}
        <Card padding={0}>
          <div className="col gap-2" style={{ padding: "20px 20px 12px" }}>
            <div className="tiny">{sameDay(selected, TODAY) ? "Aujourd'hui" : fmtRel(selected)}</div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 28, color: "var(--ink)", lineHeight: 1.05 }}>
              {DAYS_LONG[selected.getDay()].charAt(0).toUpperCase() + DAYS_LONG[selected.getDay()].slice(1)} {selected.getDate()}
              <span style={{ color: "var(--ink-3)" }}> {MONTHS[selected.getMonth()]}</span>
            </div>
            <Button variant="soft" icon="plus" onClick={() => openForm({ date: ymd(selected) })} style={{ alignSelf: "flex-start", marginTop: 6 }}>
              Ajouter ce jour
            </Button>
          </div>
          <div style={{ height: 1, background: "var(--line)", margin: "8px 0" }} />
          <div className="col gap-2" style={{ padding: 16 }}>
            {dayItems.length === 0 ? (
              <div className="muted small" style={{ padding: 16, textAlign: "center" }}>
                Aucune tâche ni événement
              </div>
            ) : (
              dayItems.map(it => <TaskRow key={it.id} item={it} date={selected} onStatusChange={onStatusChange} onEdit={onEdit} dense />)
            )}
          </div>
        </Card>
      </div>

      {/* Legend */}
      <Card padding={16}>
        <div className="row gap-4" style={{ flexWrap: "wrap" }}>
          <div className="tiny" style={{ marginRight: 8 }}>Légende</div>
          {Object.entries(STATES).map(([k, s]) => (
            <span key={k} className="row gap-1 small" style={{ color: "var(--ink-2)" }}>
              <span style={{ width: 10, height: 10, borderRadius: 3, background: s.bg, borderLeft: `2px solid ${s.color}` }} />
              {s.label}
            </span>
          ))}
          <div style={{ width: 1, height: 16, background: "var(--line)" }} />
          {Object.entries(KINDS).filter(([k]) => k !== "task").map(([k, kk]) => (
            <span key={k} className="row gap-1 small" style={{ color: "var(--ink-2)" }}>
              <span style={{ width: 10, height: 10, borderRadius: 3, background: kk.bg, borderLeft: `2px solid ${kk.color}` }} />
              {kk.label}
            </span>
          ))}
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { CalendarView });
