const CoupleScreen = () => {
  const {
    snapshot,
    updateCoupleGoal,
    updateCoupleDailyClose
  } = useAinaApp();
  const [goalTitle, setGoalTitle] = React.useState("");
  const [goalWhy, setGoalWhy] = React.useState("");
  const [closeState, setCloseState] = React.useState("partial");
  const [closeNote, setCloseNote] = React.useState("");

  React.useEffect(() => {
    if (!snapshot?.couple) {
      return;
    }

    setGoalTitle(snapshot.couple.goal?.title || "");
    setGoalWhy(snapshot.couple.goal?.why || "");
    setCloseState(snapshot.couple.dailyClose?.status || snapshot.couple.status || "partial");
    setCloseNote(snapshot.couple.dailyClose?.note || "");
  }, [snapshot]);

  if (!snapshot?.couple) {
    return <LoadingState title="Pareja" body="Cargando datos compartidos..." />;
  }

  const couple = snapshot.couple;
  const weeklyHistory = couple.weeklyHistory || [];

  return (
    <div
      className="noscroll"
      style={{
        height: "100%",
        overflowY: "auto",
        padding: "54px 16px 110px"
      }}
    >
      <ScreenTitle sub="Modo pareja">Nosotros</ScreenTitle>

      <Glass padding={18} radius={26} style={{ marginBottom: 12 }}>
        <SectionLabel icon={<I.Target size={12} />}>Meta comun</SectionLabel>
        <input
          value={goalTitle}
          onChange={(event) => setGoalTitle(event.target.value)}
          placeholder="Que os importa a los dos esta semana"
          style={{
            width: "100%",
            marginBottom: 12,
            background: "transparent",
            border: "none",
            outline: "none",
            color: "#fff",
            fontFamily: '"Instrument Serif", serif',
            fontSize: 26,
            lineHeight: 1.15,
            letterSpacing: "-0.02em"
          }}
        />
        <textarea
          value={goalWhy}
          onChange={(event) => setGoalWhy(event.target.value)}
          placeholder="Por que importa esta meta para los dos"
          style={{
            width: "100%",
            minHeight: 86,
            padding: "10px 12px",
            borderRadius: 12,
            background: "rgba(0,0,0,0.18)",
            border: "0.5px solid rgba(255,255,255,0.08)",
            fontSize: 13,
            lineHeight: 1.5,
            color: "rgba(255,255,255,0.8)",
            outline: "none",
            resize: "none",
            fontFamily: "inherit"
          }}
        />

        <div style={{ marginTop: 14 }}>
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              marginBottom: 6,
              fontSize: 11,
              letterSpacing: "0.12em",
              textTransform: "uppercase",
              color: "rgba(255,255,255,0.5)"
            }}
          >
            <span>Progreso</span>
            <span style={{ color: "#fff", fontVariantNumeric: "tabular-nums" }}>
              {couple.completionRate || 0}%
            </span>
          </div>
          <div
            style={{
              height: 8,
              borderRadius: 4,
              overflow: "hidden",
              background: "rgba(255,255,255,0.08)",
              display: "flex"
            }}
          >
            <div
              style={{
                width: `${snapshot.shared?.averageScore || 0}%`,
                background: AINA.v
              }}
            />
            <div
              style={{
                width: `${couple.completionRate || 0}%`,
                background: AINA.a
              }}
            />
          </div>
        </div>

        <div style={{ marginTop: 14, display: "flex", gap: 8 }}>
          <PillBtn
            primary
            onClick={() =>
              updateCoupleGoal({
                title: goalTitle,
                why: goalWhy
              }).catch(() => null)
            }
            style={{ flex: 1 }}
          >
            Guardar meta
          </PillBtn>
        </div>
      </Glass>

      <Glass padding={16} style={{ marginBottom: 12 }}>
        <SectionLabel icon={<I.Moon size={12} />}>Cierre del dia · juntos</SectionLabel>
        <div style={{ display: "flex", gap: 8, marginBottom: 12 }}>
          {[
            { id: "done", label: "Cumplido", emoji: "✓", color: "oklch(0.78 0.14 150)" },
            { id: "partial", label: "A medias", emoji: "~", color: "oklch(0.82 0.14 80)" },
            { id: "missed", label: "No", emoji: "×", color: "oklch(0.74 0.13 18)" }
          ].map((option) => {
            const active = closeState === option.id;
            return (
              <button
                key={option.id}
                onClick={() => setCloseState(option.id)}
                style={{
                  flex: 1,
                  height: 56,
                  borderRadius: 16,
                  background: active
                    ? `${option.color.replace(")", " / 0.22)")}`
                    : "rgba(255,255,255,0.06)",
                  border: `0.5px solid ${
                    active ? option.color : "rgba(255,255,255,0.14)"
                  }`,
                  color: "#fff",
                  cursor: "pointer",
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  justifyContent: "center",
                  gap: 2,
                  fontFamily: "inherit"
                }}
              >
                <span
                  style={{
                    fontFamily: '"Instrument Serif", serif',
                    fontSize: 22,
                    color: active ? option.color : "rgba(255,255,255,0.7)",
                    lineHeight: 1
                  }}
                >
                  {option.emoji}
                </span>
                <span style={{ fontSize: 11, fontWeight: 590, letterSpacing: "0.04em" }}>
                  {option.label}
                </span>
              </button>
            );
          })}
        </div>

        <textarea
          value={closeNote}
          onChange={(event) => setCloseNote(event.target.value)}
          placeholder="Nota de cierre - como os habeis sentido hoy"
          style={{
            width: "100%",
            minHeight: 64,
            resize: "none",
            padding: 12,
            borderRadius: 12,
            background: "rgba(0,0,0,0.22)",
            border: "0.5px solid rgba(255,255,255,0.1)",
            color: "#fff",
            fontFamily: "inherit",
            fontSize: 13,
            lineHeight: 1.5,
            outline: "none"
          }}
        />
        <div
          style={{
            fontSize: 12,
            lineHeight: 1.45,
            color: "rgba(255,255,255,0.52)",
            marginTop: 10
          }}
        >
          {couple.dailyClose
            ? `Ultimo cierre guardado a las ${formatPreviewTime(couple.dailyClose.updatedAt)}.`
            : couple.statusLabel}
        </div>
        <div style={{ marginTop: 12 }}>
          <PillBtn
            primary
            onClick={() =>
              updateCoupleDailyClose({
                status: closeState,
                note: closeNote
              }).catch(() => null)
            }
            style={{ width: "100%" }}
          >
            Guardar cierre
          </PillBtn>
        </div>
      </Glass>

      <Glass padding={16} style={{ marginBottom: 12 }}>
        <SectionLabel icon={<I.Star size={12} />}>Metricas compartidas</SectionLabel>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          {[
            {
              label: "Trackers cerrados",
              value: `${couple.completedTrackers}/${couple.totalTrackers}`,
              sub: "hoy"
            },
            {
              label: "Racha conjunta",
              value: `${couple.jointStreakDays || 0}`,
              sub: "dias"
            },
            {
              label: "Media semanal",
              value: `${couple.weeklyAverageCompletion || 0}%`,
              sub: "6 semanas"
            },
            {
              label: "Tendencia",
              value: `${couple.weeklyTrend >= 0 ? "+" : ""}${couple.weeklyTrend || 0}`,
              sub: "pts vs anterior"
            }
          ].map((metric) => (
            <div
              key={metric.label}
              style={{
                padding: 12,
                borderRadius: 14,
                background: "rgba(255,255,255,0.04)",
                border: "0.5px solid rgba(255,255,255,0.08)"
              }}
            >
              <div
                style={{
                  fontSize: 10,
                  letterSpacing: "0.14em",
                  textTransform: "uppercase",
                  color: "rgba(255,255,255,0.5)"
                }}
              >
                {metric.label}
              </div>
              <div
                className="serif"
                style={{ fontSize: 30, lineHeight: 1, marginTop: 6 }}
              >
                {metric.value}
              </div>
              <div style={{ fontSize: 11, color: "rgba(255,255,255,0.5)", marginTop: 4 }}>
                {metric.sub}
              </div>
            </div>
          ))}
        </div>
      </Glass>

      <Glass padding={16} style={{ marginBottom: 12 }}>
        <SectionLabel icon={<I.Stream size={12} />}>Historico · semanas</SectionLabel>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {weeklyHistory.length ? (
            weeklyHistory.map((week) => (
              <div
                key={week.weekKey}
                style={{ display: "flex", alignItems: "center", gap: 12 }}
              >
                <div style={{ width: 88, fontSize: 12, color: "rgba(255,255,255,0.7)" }}>
                  {week.shortLabel}
                </div>
                <div style={{ flex: 1, display: "flex", flexDirection: "column", gap: 3 }}>
                  <MiniBars
                    values={Array.from({ length: Math.max(week.elapsedDays || 1, 1) }, () => week.completionRate)}
                    color={AINA.v}
                    height={14}
                  />
                  <MiniBars
                    values={Array.from({ length: Math.max(week.elapsedDays || 1, 1) }, () => week.averageScore)}
                    color={AINA.a}
                    height={14}
                  />
                </div>
                <div
                  style={{
                    width: 8,
                    height: 8,
                    borderRadius: 4,
                    background: week.isCurrentWeek ? "#fff" : "rgba(255,255,255,0.4)"
                  }}
                />
              </div>
            ))
          ) : (
            <div style={{ fontSize: 13, color: "rgba(255,255,255,0.55)" }}>
              Todavia no hay semanas con actividad.
            </div>
          )}
        </div>
      </Glass>
    </div>
  );
};

window.CoupleScreen = CoupleScreen;
