// ---------- Calendar page — studio cadence view ----------

const CalendarPage = ({ onOpenProject, onOpenMobileMenu }) => {
  // May 2026 — anchor
  const [view, setView] = React.useState("month");
  const [monthOffset, setMonthOffset] = React.useState(0);

  // Build events from projects + add some shoots
  const baseEvents = [
    { day: 2, kind: "shoot", project: "Cambridge Listing", title: "Location shoot", accent: "harbor" },
    { day: 9, kind: "milestone", project: "Cambridge Listing", title: "Assembly cut", accent: "harbor" },
    { day: 11, kind: "review", project: "Lucius Fashion Ep.", title: "Picture lock review", accent: "amber" },
    { day: 15, kind: "review", project: "Cambridge Listing", title: "Cut 03 — Client review", accent: "harbor", active: true },
    { day: 18, kind: "shoot", project: "Bluehill Launch", title: "Product shoot", accent: "teal" },
    { day: 22, kind: "delivery", project: "OOO Episode 14", title: "Final delivery", accent: "lavender" },
    { day: 24, kind: "delivery", project: "Cambridge Listing", title: "Final delivery", accent: "harbor" },
    { day: 26, kind: "shoot", project: "Beacon Hill", title: "Walkthrough shoot", accent: "harbor" },
    { day: 28, kind: "milestone", project: "Lucius Fashion Ep.", title: "Picture lock", accent: "amber" },
    { day: 30, kind: "review", project: "Bluehill Launch", title: "Storyboard sign-off", accent: "teal" },
  ];

  // Demo events are anchored to May 2026; adjacent months still render accurate grids.
  const displayDate = new Date(2026, 4 + monthOffset, 1);
  const monthName = displayDate.toLocaleString("en-US", { month: "long", year: "numeric" });
  const monthShort = displayDate.toLocaleString("en-US", { month: "short" }).toUpperCase();
  const daysInMonth = new Date(displayDate.getFullYear(), displayDate.getMonth() + 1, 0).getDate();
  const firstDayOfWeek = displayDate.getDay(); // 0=Sun
  const today = monthOffset === 0 ? 23 : null;
  const events = monthOffset === 0 ? baseEvents : [];
  const weekDays = Array.from({ length: 7 }, (_, i) => Math.min(daysInMonth, (monthOffset === 0 ? 18 : 1) + i));

  const cells = [];
  for (let i = 0; i < firstDayOfWeek; i++) cells.push({ pad: true });
  for (let d = 1; d <= daysInMonth; d++) {
    cells.push({ day: d, events: events.filter(e => e.day === d), isToday: d === today });
  }
  while (cells.length % 7 !== 0) cells.push({ pad: true });

  return (
    <div>
      <Topbar
        eyebrow="WORKSPACE"
        title="Studio calendar"
        onOpenMobileMenu={onOpenMobileMenu}
        actions={
          <>
            <Button variant="ghost" size="md" icon={<window.Icon.Calendar size={13} />}>Sync to Google</Button>
            <Button variant="primary" size="md" icon={<window.Icon.Plus size={13} />}>Add event</Button>
          </>
        }
      />

      <div className="hd-page-pad" style={{ padding: "20px 32px 60px", display: "flex", flexDirection: "column", gap: 16 }}>
        {/* Header strip */}
        <Card className="hd-mobile-row" style={{ padding: "14px 18px", display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: 12 }}>
          <div className="hd-mobile-row" style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{ display: "flex", gap: 4 }}>
              <window.IconButton iconName="ChevronL" label="Previous" onClick={() => setMonthOffset(m => m - 1)} />
              <window.IconButton iconName="ChevronR" label="Next" onClick={() => setMonthOffset(m => m + 1)} />
            </div>
            <Button variant="ghost" size="sm" onClick={() => setMonthOffset(0)}>Today</Button>
            <div style={{ fontFamily: "var(--serif)", fontSize: 22, fontWeight: 500, letterSpacing: "-0.01em", color: "var(--white)", marginLeft: 8 }}>
              {monthName}
            </div>
          </div>

          <div className="hd-mobile-row" style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div className="hd-scroll-x" style={{ display: "flex", gap: 14, fontSize: 11.5, color: "var(--warm-gray)", width: "100%" }}>
              <Legend tone="harbor" label="Reviews" />
              <Legend tone="amber" label="Milestones" />
              <Legend tone="teal" label="Shoots" />
              <Legend tone="lavender" label="Deliveries" />
            </div>
            <div style={{ display: "flex", gap: 4, padding: 3, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.05)", borderRadius: 8 }}>
              {["month", "week", "list"].map(v => (
                <button
                  key={v}
                  onClick={() => setView(v)}
                  style={{
                    padding: "5px 10px", borderRadius: 6,
                    background: view === v ? "rgba(255,255,255,0.06)" : "transparent",
                    color: view === v ? "var(--white)" : "var(--warm-gray)",
                    border: "none", fontSize: 12, fontFamily: "var(--sans)", cursor: "pointer",
                    textTransform: "capitalize",
                  }}
                >{v}</button>
              ))}
            </div>
          </div>
        </Card>

        {view === "month" && (
          <Card className="hd-calendar-card" style={{ padding: 0, overflowX: "auto", overflowY: "hidden" }}>
            {/* Weekday header */}
            <div className="hd-calendar-weekdays" style={{ display: "grid", gridTemplateColumns: "repeat(7, minmax(0, 1fr))", borderBottom: "1px solid rgba(255,255,255,0.05)", minWidth: 560 }}>
              {["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"].map(d => (
                <div key={d} className="micro hd-calendar-weekday" style={{ padding: "10px 14px", color: "var(--warm-gray)", fontSize: 9.5 }}>{d}</div>
              ))}
            </div>
            {/* Day grid */}
            <div className="hd-calendar-month-grid" style={{ display: "grid", gridTemplateColumns: "repeat(7, minmax(0, 1fr))", gridAutoRows: "minmax(112px, 1fr)", minWidth: 560 }}>
              {cells.map((c, i) => (
                <div key={i} className="hd-calendar-day-cell" style={{
                  borderRight: (i % 7 !== 6) ? "1px solid rgba(255,255,255,0.04)" : "none",
                  borderBottom: "1px solid rgba(255,255,255,0.04)",
                  padding: 8,
                  background: c.isToday ? "rgba(29,78,216,0.06)" : "transparent",
                  position: "relative",
                  minHeight: 112,
                }}>
                  {!c.pad && (
                    <>
                      <div style={{
                        fontSize: 12, fontWeight: c.isToday ? 600 : 400,
                        color: c.isToday ? "var(--harbor-2)" : "var(--white)",
                        marginBottom: 6,
                        display: "inline-flex", alignItems: "center", gap: 6,
                      }}>
                        {c.isToday && <span style={{ width: 6, height: 6, borderRadius: 99, background: "var(--harbor-2)" }} />}
                        {c.day}
                      </div>
                      <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
                        {c.events.map((e, idx) => {
                          const tone = STATUS_TONES[e.accent];
                          return (
                            <div
                              key={idx}
                              className="hd-calendar-event"
                              onClick={() => {
                                const match = HD.projects.find(p => p.name.includes(e.project) || e.project.includes(p.name.split(" ")[0]));
                                if (match) onOpenProject(match.id);
                              }}
                              style={{
                                background: tone.bg, border: `1px solid ${tone.bd}`,
                                color: tone.fg, padding: "3px 6px",
                                borderRadius: 5, fontSize: 10.5,
                                cursor: "pointer", overflow: "hidden",
                                whiteSpace: "nowrap", textOverflow: "ellipsis",
                                lineHeight: 1.3,
                              }}
                            >
                              {e.title}
                            </div>
                          );
                        })}
                      </div>
                    </>
                  )}
                </div>
              ))}
            </div>
          </Card>
        )}

        {view === "list" && (
          <Card style={{ padding: 0, overflowX: "auto", overflowY: "hidden" }}>
            <div style={{ padding: "16px 20px", borderBottom: "1px solid rgba(255,255,255,0.05)" }}>
              <SectionHeader eyebrow="UPCOMING" title={`${events.length} events this month`} dense />
            </div>
            <div>
              {events.length === 0 ? (
                <div style={{ padding: "32px 20px", textAlign: "center", color: "var(--warm-gray)", fontSize: 13 }}>
                  No events scheduled for {monthName}.
                </div>
              ) : events.map((e, i) => {
                const tone = STATUS_TONES[e.accent];
                return (
                  <div key={i} className="hd-row hd-calendar-list-row" style={{
                    display: "grid", gridTemplateColumns: "60px minmax(0,1fr) 130px 110px",
                    gap: 16, padding: "14px 20px", alignItems: "center",
                    borderBottom: i === events.length - 1 ? "none" : "1px solid rgba(255,255,255,0.04)",
                    cursor: "pointer",
                    minWidth: 520,
                  }}>
                    <div style={{
                      padding: "8px 0", borderRadius: 8,
                      background: "rgba(255,255,255,0.025)",
                      border: "1px solid rgba(255,255,255,0.06)",
                      textAlign: "center", flexShrink: 0,
                    }}>
                      <div className="micro" style={{ color: "var(--warm-gray)", fontSize: 9 }}>{monthShort}</div>
                      <div style={{ fontFamily: "var(--serif)", fontSize: 18, lineHeight: 1, color: "var(--white)" }}>{e.day}</div>
                    </div>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 500, color: "var(--white)" }}>{e.title}</div>
                      <div style={{ fontSize: 11.5, color: "var(--warm-gray)", marginTop: 2 }}>{e.project}</div>
                    </div>
                    <div className="hd-calendar-list-status">
                      <StatusBadge tone={e.accent} label={e.kind.charAt(0).toUpperCase() + e.kind.slice(1)} size="sm" />
                    </div>
                    <div className="hd-calendar-list-meta" style={{ textAlign: "right", fontSize: 11.5, color: "var(--warm-gray)" }}>
                      {e.day < 23 ? "Past" : e.day === 23 ? "Today" : `in ${e.day - 23}d`}
                    </div>
                  </div>
                );
              })}
            </div>
          </Card>
        )}

        {view === "week" && (
          <Card className="hd-calendar-card" style={{ padding: 0, overflowX: "auto", overflowY: "hidden" }}>
            {/* Week strip */}
            <div className="hd-calendar-week-grid" style={{ display: "grid", gridTemplateColumns: "repeat(7, minmax(0, 1fr))", borderBottom: "1px solid rgba(255,255,255,0.05)", minWidth: 560 }}>
              {weekDays.map(d => (
                <div key={d} className="hd-calendar-day-cell" style={{
                  padding: 14, textAlign: "left",
                  borderRight: d !== weekDays[weekDays.length - 1] ? "1px solid rgba(255,255,255,0.04)" : "none",
                  background: d === today ? "rgba(29,78,216,0.06)" : "transparent",
                }}>
                  <div className="micro" style={{ color: "var(--warm-gray)", fontSize: 9.5 }}>
                    {new Date(displayDate.getFullYear(), displayDate.getMonth(), d).toLocaleString("en-US", { weekday: "short" }).toUpperCase()}
                  </div>
                  <div style={{ fontFamily: "var(--serif)", fontSize: 22, color: d === today ? "var(--harbor-2)" : "var(--white)", letterSpacing: "-0.01em", marginTop: 2, fontWeight: d === today ? 600 : 500 }}>{d}</div>
                </div>
              ))}
            </div>
            <div className="hd-calendar-week-body" style={{ display: "grid", gridTemplateColumns: "repeat(7, minmax(0, 1fr))", minHeight: 280, minWidth: 560 }}>
              {weekDays.map(d => (
                <div key={d} className="hd-calendar-day-cell" style={{
                  padding: 10, borderRight: d !== weekDays[weekDays.length - 1] ? "1px solid rgba(255,255,255,0.04)" : "none",
                  display: "flex", flexDirection: "column", gap: 4,
                }}>
                  {events.filter(e => e.day === d).map((e, idx) => {
                    const tone = STATUS_TONES[e.accent];
                    return (
                      <div key={idx} className="hd-calendar-event" style={{
                        background: tone.bg, border: `1px solid ${tone.bd}`,
                        color: tone.fg, padding: "6px 8px",
                        borderRadius: 6, fontSize: 11,
                      }}>
                        <div style={{ fontWeight: 500 }}>{e.title}</div>
                        <div style={{ opacity: 0.7, marginTop: 2, fontSize: 10 }}>{e.project}</div>
                      </div>
                    );
                  })}
                </div>
              ))}
            </div>
          </Card>
        )}
      </div>
    </div>
  );
};

const Legend = ({ tone, label }) => {
  const t = STATUS_TONES[tone];
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
      <span style={{ width: 8, height: 8, borderRadius: 99, background: t.dot }} />
      {label}
    </span>
  );
};

window.CalendarPage = CalendarPage;
