const CalendarScreen = () => {
  const { snapshot, selectedProfile, selectProfile } = useAinaApp();
  const [selectedDateKey, setSelectedDateKey] = React.useState("");

  React.useEffect(() => {
    const days = snapshot?.home?.monthly?.days || [];
    if (!days.length) {
      return;
    }

    if (days.some((day) => day.dateKey === selectedDateKey)) {
      return;
    }

    const fallback =
      days.find((day) => day.isToday) ||
      [...days].reverse().find((day) => day.isCurrentMonth && day.activityCount > 0) ||
      days.find((day) => day.isCurrentMonth) ||
      days[0];

    setSelectedDateKey(fallback?.dateKey || "");
  }, [snapshot, selectedDateKey]);

  if (!snapshot?.home?.monthly || !selectedProfile) {
    return <LoadingState title="Mes" body="Cargando calendario real..." />;
  }

  const month = snapshot.home.monthly;
  const selectedDay =
    month.days.find((day) => day.dateKey === selectedDateKey) || month.days[0] || null;
  const detail = selectedDay?.detail || {};
  const selectedWho = getWhoForName(selectedProfile.name);

  return (
    <div
      className="noscroll"
      style={{
        height: "100%",
        overflowY: "auto",
        padding: "54px 16px 110px"
      }}
    >
      <ScreenTitle sub={String(month.label || "").replace(/^./, (match) => match.toUpperCase())}>
        Mes
      </ScreenTitle>

      <div style={{ display: "flex", gap: 8, marginBottom: 12 }}>
        {snapshot.profiles.map((profile) => {
          const active = profile.id === selectedProfile.id;
          return (
            <button
              key={profile.id}
              onClick={() => selectProfile(profile.id).catch(() => null)}
              style={{
                flex: 1,
                height: 38,
                borderRadius: 19,
                padding: "0 10px",
                background: active ? "rgba(255,255,255,0.96)" : "rgba(255,255,255,0.06)",
                color: active ? "#0a0612" : "#fff",
                border: active ? "none" : "0.5px solid rgba(255,255,255,0.14)",
                display: "inline-flex",
                alignItems: "center",
                justifyContent: "center",
                gap: 8,
                fontFamily: "inherit",
                fontSize: 13,
                fontWeight: 600,
                cursor: "pointer"
              }}
            >
              <Avatar who={getWhoForName(profile.name)} size={18} ring={false} />
              {profile.name}
            </button>
          );
        })}
      </div>

      <Glass padding={14} style={{ marginBottom: 12 }}>
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "repeat(7, 1fr)",
            gap: 4,
            marginBottom: 8
          }}
        >
          {["L", "M", "X", "J", "V", "S", "D"].map((label) => (
            <div
              key={label}
              style={{
                fontSize: 10,
                letterSpacing: "0.1em",
                color: "rgba(255,255,255,0.45)",
                textAlign: "center",
                fontWeight: 590
              }}
            >
              {label}
            </div>
          ))}
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(7, 1fr)", gap: 4 }}>
          {month.days.map((day) => {
            const active = day.dateKey === selectedDay?.dateKey;
            const intensity = day.score / 100;
            return (
              <button
                key={day.dateKey}
                onClick={() => setSelectedDateKey(day.dateKey)}
                style={{
                  aspectRatio: "1",
                  borderRadius: 10,
                  background: !day.isCurrentMonth
                    ? "rgba(255,255,255,0.03)"
                    : `linear-gradient(135deg,
                      oklch(0.78 ${0.06 + intensity * 0.1} 28 / ${0.15 + intensity * 0.45}),
                      oklch(0.78 ${0.06 + intensity * 0.1} 350 / ${0.15 + intensity * 0.45}))`,
                  border: active ? "1.5px solid #fff" : "0.5px solid rgba(255,255,255,0.08)",
                  color: day.isCurrentMonth ? "#fff" : "rgba(255,255,255,0.25)",
                  fontSize: 13,
                  fontWeight: 590,
                  fontVariantNumeric: "tabular-nums",
                  cursor: "pointer",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  position: "relative",
                  fontFamily: "inherit"
                }}
              >
                {day.dayNumber}
                {day.isToday && (
                  <div
                    style={{
                      position: "absolute",
                      bottom: 3,
                      right: 3,
                      width: 4,
                      height: 4,
                      borderRadius: 2,
                      background: "#fff",
                      opacity: 0.85
                    }}
                  />
                )}
              </button>
            );
          })}
        </div>

        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            marginTop: 12,
            paddingTop: 10,
            borderTop: "0.5px solid rgba(255,255,255,0.1)",
            fontSize: 10,
            color: "rgba(255,255,255,0.5)",
            letterSpacing: "0.04em"
          }}
        >
          <span>Bajo</span>
          <div style={{ display: "flex", gap: 3 }}>
            {[0.15, 0.3, 0.45, 0.6, 0.75].map((opacity, index) => (
              <div
                key={index}
                style={{
                  width: 12,
                  height: 12,
                  borderRadius: 3,
                  background: `linear-gradient(135deg, oklch(0.78 0.1 28 / ${opacity}), oklch(0.78 0.1 350 / ${opacity}))`
                }}
              />
            ))}
          </div>
          <span>Alto</span>
        </div>
      </Glass>

      {selectedDay && (
        <Glass padding={16} radius={22}>
          <div
            style={{
              display: "flex",
              alignItems: "baseline",
              gap: 10,
              marginBottom: 14
            }}
          >
            <div
              className="serif"
              style={{
                fontSize: 42,
                lineHeight: 1,
                letterSpacing: "-0.02em"
              }}
            >
              {selectedDay.dayNumber}
            </div>
            <div style={{ fontSize: 13, color: "rgba(255,255,255,0.55)" }}>
              · {detail.label || selectedDay.shortLabel}
            </div>
            <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
              <div style={{ textAlign: "center" }}>
                <div style={{ fontSize: 14, fontWeight: 590, color: selectedWho === "aina" ? AINA.a : AINA.v }}>
                  {selectedDay.score}%
                </div>
                <div style={{ fontSize: 9, color: "rgba(255,255,255,0.5)", letterSpacing: "0.1em" }}>
                  SCORE
                </div>
              </div>
            </div>
          </div>

          <div style={{ display: "flex", gap: 8, marginBottom: 14 }}>
            <span style={{ fontSize: 18 }}>🌿</span>
            <div style={{ flex: 1 }}>
              <div
                style={{
                  fontSize: 11,
                  color: "rgba(255,255,255,0.5)",
                  letterSpacing: "0.12em",
                  textTransform: "uppercase"
                }}
              >
                Foco
              </div>
              <div style={{ fontSize: 14, marginTop: 2 }}>
                {detail.focus || detail.journal || "Sin foco o nota guardada"}
              </div>
            </div>
          </div>

          <div style={{ marginBottom: 12 }}>
            <div
              style={{
                fontSize: 11,
                color: "rgba(255,255,255,0.5)",
                letterSpacing: "0.12em",
                textTransform: "uppercase",
                marginBottom: 6
              }}
            >
              Habitos · {detail.completedHabitCount || 0}/{detail.habitCount || 0}
            </div>
            <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
              {(detail.completedHabitCount || 0) > 0 && (
                <span
                  style={{
                    fontSize: 11,
                    padding: "3px 8px",
                    borderRadius: 8,
                    background: "rgba(255,255,255,0.08)",
                    border: "0.5px solid rgba(255,255,255,0.12)"
                  }}
                >
                  ✓ {detail.completedHabitCount} hechos
                </span>
              )}
              {(detail.habitCount || 0) - (detail.completedHabitCount || 0) > 0 && (
                <span
                  style={{
                    fontSize: 11,
                    padding: "3px 8px",
                    borderRadius: 8,
                    background: "rgba(255,255,255,0.02)",
                    border: "0.5px dashed rgba(255,255,255,0.18)",
                    color: "rgba(255,255,255,0.45)"
                  }}
                >
                  ○ {(detail.habitCount || 0) - (detail.completedHabitCount || 0)} pendientes
                </span>
              )}
            </div>
          </div>

          <div>
            <div
              style={{
                fontSize: 11,
                color: "rgba(255,255,255,0.5)",
                letterSpacing: "0.12em",
                textTransform: "uppercase",
                marginBottom: 6
              }}
            >
              Tareas · {detail.completedTaskCount || 0}/{detail.taskCount || 0}
            </div>
            <div style={{ fontSize: 13, lineHeight: 1.7, color: "rgba(255,255,255,0.85)" }}>
              {(detail.completedTasks || []).map((task) => (
                <div key={`done-${task.id}`}>✓ {task.title}</div>
              ))}
              {(detail.pendingTasks || []).map((task) => (
                <div key={`pending-${task.id}`} style={{ opacity: 0.55 }}>
                  ○ {task.title}
                </div>
              ))}
              {!detail.completedTasks?.length && !detail.pendingTasks?.length && (
                <div style={{ opacity: 0.55 }}>No hubo tareas ese dia.</div>
              )}
            </div>
          </div>
        </Glass>
      )}
    </div>
  );
};

window.CalendarScreen = CalendarScreen;
