const TimelineScreen = () => {
  const { snapshot, viewer, addComment, reactComment } = useAinaApp();
  const [filter, setFilter] = React.useState("all");
  const [draft, setDraft] = React.useState("");

  if (!snapshot || !viewer) {
    return <LoadingState title="Timeline" body="Cargando actividad compartida..." />;
  }

  const mergedFeed = [
    ...(snapshot.timeline || []).map((item) => ({
      id: `activity-${item.id}`,
      createdAt: item.createdAt,
      whoId: item.actorProfileId,
      whoName: item.actorName,
      title: item.summary,
      body: item.detail || "",
      kind: "activity"
    })),
    ...(snapshot.comments || []).map((comment) => ({
      id: `comment-${comment.id}`,
      createdAt: comment.createdAt,
      whoId: comment.authorProfileId,
      whoName: comment.authorName,
      title: "Comentario",
      body: comment.body,
      kind: "comment",
      comment
    }))
  ]
    .sort((left, right) => String(right.createdAt).localeCompare(String(left.createdAt)))
    .filter((item) => (filter === "all" ? true : item.whoId === filter));

  const submitComment = async () => {
    if (!draft.trim()) {
      return;
    }

    await addComment(draft.trim()).catch(() => null);
    setDraft("");
  };

  return (
    <div
      className="noscroll"
      style={{
        height: "100%",
        overflowY: "auto",
        padding: "54px 16px 110px"
      }}
    >
      <ScreenTitle sub="Hoy · feed compartido">Timeline</ScreenTitle>

      <Glass padding={14} style={{ marginBottom: 14 }}>
        <textarea
          value={draft}
          onChange={(event) => setDraft(event.target.value)}
          placeholder="Escribe algo bonito, util o importante para el otro"
          style={{
            width: "100%",
            minHeight: 74,
            resize: "none",
            padding: 12,
            borderRadius: 14,
            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={{ marginTop: 10, display: "flex", justifyContent: "flex-end" }}>
          <PillBtn primary onClick={submitComment}>
            Enviar
          </PillBtn>
        </div>
      </Glass>

      <div style={{ display: "flex", gap: 8, marginBottom: 14 }}>
        {[
          { id: "all", label: "Todo" },
          ...snapshot.profiles.map((profile) => ({
            id: profile.id,
            label: profile.name,
            who: getWhoForName(profile.name)
          }))
        ].map((item) => {
          const active = filter === item.id;
          return (
            <button
              key={item.id}
              onClick={() => setFilter(item.id)}
              style={{
                height: 34,
                padding: "0 14px",
                borderRadius: 17,
                background: active ? "rgba(255,255,255,0.95)" : "rgba(255,255,255,0.06)",
                color: active ? "#0a0612" : "rgba(255,255,255,0.85)",
                border: active ? "none" : "0.5px solid rgba(255,255,255,0.14)",
                backdropFilter: active ? "none" : "blur(18px)",
                fontSize: 13,
                fontWeight: 590,
                cursor: "pointer",
                display: "inline-flex",
                alignItems: "center",
                gap: 6,
                fontFamily: "inherit"
              }}
            >
              {item.who && <Avatar who={item.who} size={18} ring={false} />}
              {item.label}
            </button>
          );
        })}
      </div>

      <div style={{ position: "relative", paddingLeft: 30 }}>
        <div
          style={{
            position: "absolute",
            left: 17,
            top: 14,
            bottom: 14,
            width: 1,
            background:
              "linear-gradient(180deg, transparent, rgba(255,255,255,0.18) 12%, rgba(255,255,255,0.18) 88%, transparent)"
          }}
        />

        {mergedFeed.length ? (
          mergedFeed.map((item) => (
            <TimelineItem
              key={item.id}
              item={item}
              onReact={(reactionType) =>
                reactComment(item.comment.id, reactionType).catch(() => null)
              }
            />
          ))
        ) : (
          <Glass padding={14} radius={18}>
            <div style={{ fontSize: 13, lineHeight: 1.55, color: "rgba(255,255,255,0.6)" }}>
              Todavia no hay actividad ni comentarios guardados.
            </div>
          </Glass>
        )}
      </div>
    </div>
  );
};

const TimelineItem = ({ item, onReact }) => {
  const who = getWhoForName(item.whoName);

  return (
    <div style={{ position: "relative", marginBottom: 14 }}>
      <div
        style={{
          position: "absolute",
          left: -22,
          top: 14,
          width: 12,
          height: 12,
          borderRadius: "50%",
          background: "#0a0612",
          border: `2px solid ${who === "victor" ? AINA.v : AINA.a}`
        }}
      />

      <Glass padding={14} radius={18} soft={item.kind !== "comment"}>
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 8,
            marginBottom: 8
          }}
        >
          <Avatar who={who} size={22} ring={false} />
          <span style={{ fontSize: 13, fontWeight: 590 }}>{item.whoName}</span>
          <span
            style={{
              fontSize: 11,
              color: "rgba(255,255,255,0.45)",
              marginLeft: "auto",
              fontVariantNumeric: "tabular-nums"
            }}
          >
            {formatPreviewTime(item.createdAt)}
          </span>
        </div>

        <div style={{ display: "flex", alignItems: "flex-start", gap: 8 }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 500, lineHeight: 1.35 }}>
              {item.title}
            </div>
            {item.body ? (
              <div
                style={{
                  fontSize: 13,
                  color: "rgba(255,255,255,0.72)",
                  lineHeight: 1.5,
                  marginTop: 4
                }}
              >
                {item.body}
              </div>
            ) : null}
          </div>
          {item.kind === "comment" && (
            <div
              style={{
                fontSize: 10,
                letterSpacing: "0.12em",
                textTransform: "uppercase",
                color: "rgba(255,255,255,0.45)"
              }}
            >
              Comment
            </div>
          )}
        </div>

        {item.kind === "comment" && (
          <div style={{ display: "flex", gap: 6, marginTop: 10, flexWrap: "wrap" }}>
            {item.comment.reactions.map((reaction) => (
              <ReactChip
                key={reaction.type}
                emoji={
                  {
                    animo: "💪",
                    orgullo: "🤍",
                    fuego: "🔥"
                  }[reaction.type] || "✨"
                }
                count={reaction.count}
                active={reaction.reacted}
                onClick={() => onReact(reaction.type)}
              />
            ))}
          </div>
        )}
      </Glass>
    </div>
  );
};

window.TimelineScreen = TimelineScreen;
