import { useTranslation } from "next-i18next";
import Container from "components/services/widget/container";
import useWidgetAPI from "utils/proxy/use-widget-api";
export default function Component({ service }) {
  const { widget } = service;
  const { data, error } = useWidgetAPI(widget, "items");
  if (error) {
    return <Container service={service} error={error} />;
  }
  if (!data) {
    return (
      <Container service={service}>
        {" "}
        <div className="w-full flex flex-col pl-4 pr-3">
          {" "}
          <div className="mb-3 h-3 w-24 bg-theme-700/50 rounded animate-pulse" />{" "}
          {[1, 2, 3, 4].map((i) => (
            <div key={i} className="flex flex-col gap-1 mb-3 last:mb-0">
              {" "}
              <div className="h-4 w-full bg-theme-700/50 rounded animate-pulse" />{" "}
              <div className="h-3 w-2/3 bg-theme-800/50 rounded animate-pulse" />{" "}
            </div>
          ))}{" "}
        </div>{" "}
      </Container>
    );
  }
  const limit = parseInt(widget.limit, 10) || 5;
  const items = data?.items?.slice(0, limit) || [];
  const fmtDate = (unix) => {
    if (!unix) return "";
    return new Date(unix * 1000).toLocaleDateString(undefined, {
      month: "short",
      day: "numeric",
    });
  };
  return (
    <Container service={service}>
      {" "}
      <div className="w-full flex flex-col pl-4 pr-3">
        {" "}
        <div className="mb-3 text-[10px] font-bold tracking-[0.15em] text-theme-500 uppercase">
          {" "}
          {widget.category || "FreshRSS"}{" "}
        </div>{" "}
        <ul className="flex flex-col gap-3">
          {" "}
          {items.map((item) => (
            <li key={item.id} className="flex flex-col gap-1">
              {" "}
              <a
                href={item.url}
                target="_blank"
                rel="noopener noreferrer"
                className="text-sm font-medium text-amber-200/90 hover:text-amber-100 truncate leading-snug transition-colors"
                title={item.title}
              >
                {" "}
                {item.title}{" "}
              </a>{" "}
              <div className="text-xs text-theme-500 truncate font-normal">
                {" "}
                {fmtDate(item.created_on_time)}{" "}
                {item.author && <span> · {item.author}</span>}{" "}
                {item.feed_name && <span> · {item.feed_name}</span>}{" "}
              </div>{" "}
            </li>
          ))}{" "}
        </ul>{" "}
      </div>{" "}
    </Container>
  );
}
