"use client";

import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { Avatar } from "./Avatar";
import type { Comment } from "@/lib/types";

export function CommentPreview({
  postId,
  commentCount,
  onCountChange,
}: {
  postId: string;
  commentCount: number;
  /** Lets the card's own counter follow along rather than waiting for a reload. */
  onCountChange?: (n: number) => void;
}) {
  const [comments, setComments] = useState<Comment[]>([]);
  const [index, setIndex] = useState(0);
  const [visible, setVisible] = useState(true);

  // Held in a ref so reporting the count doesn't re-trigger the fetch that
  // reported it — that pair was chasing its own tail.
  const report = useRef(onCountChange);
  report.current = onCountChange;

  useEffect(() => {
    if (commentCount === 0) return;

    fetch(`/api/posts/${postId}/comments`)
      .then((r) => (r.ok ? r.json() : []))
      .then((d: Comment[]) => {
        const list = Array.isArray(d) ? d : [];
        setComments(list.slice(0, 5));
        // So the card's counter shows the real number without a reload.
        report.current?.(list.length);
      })
      .catch(() => {});
    // Only the post: the count is what this sets, not what it reads.
  }, [postId]);

  // Cycle to the next comment every few seconds, fading out and back in so
  // the swap reads as a deliberate transition rather than a flicker.
  // How many there are, in a ref: as a dependency it remade the interval
  // on every change, and the interval's own updates kept changing it.
  const howMany = useRef(comments.length);
  howMany.current = comments.length;

  useEffect(() => {
    if (comments.length < 2) return;

    const id = setInterval(() => {
      setVisible(false);
      setTimeout(() => {
        setIndex((i) => (i + 1) % Math.max(1, howMany.current));
        setVisible(true);
      }, 380);
    }, 2600);

    return () => clearInterval(id);
    // Only whether there's more than one to cycle through.
  }, [comments.length > 1]);

  if (comments.length === 0) return null;
  const c = comments[index];
  if (!c) return null;

  return (
    <Link
      href={`/post/${postId}`}
      className="hidden sm:flex items-center gap-2 ml-auto max-w-[340px] justify-end group/preview"
    >
      <Avatar user={c.author} size={18} />
      <span
        className={`pa-pill ${visible ? "in" : "out"} flex items-center gap-1.5 bg-neutral-100 dark:bg-neutral-900 rounded-full px-3 py-1.5 text-xs min-w-0 group-hover/preview:bg-neutral-200 dark:group-hover/preview:bg-neutral-800`}
      >
        <span className="font-semibold shrink-0">{c.author.name.split(" ")[0]}:</span>
        <span className="text-neutral-600 dark:text-neutral-300 truncate">{c.text}</span>
      </span>
    </Link>
  );
}
