import { useCallback, useEffect, useRef, useState } from "react";
import { listChannels, listFeed } from "../api";
import type { ChannelWithCount, FeedFilter, FeedItem } from "../types";

export function useFeed(filter: FeedFilter) {
  const [items, setItems] = useState<FeedItem[]>([]);
  const [channels, setChannels] = useState<ChannelWithCount[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // A refresh can take half a minute, and the filter may well change while it
  // runs. Reading the filter at call time rather than capturing it keeps a
  // reload from asking for the list the user has already moved on from.
  const latest = useRef(filter);
  latest.current = filter;
  // Only the newest load may write; a slower earlier one is dropped, so an
  // out-of-order reply cannot put a stale list back on screen.
  const seq = useRef(0);

  const reload = useCallback(async () => {
    const mine = ++seq.current;
    setLoading(true);
    try {
      const [feed, chans] = await Promise.all([listFeed(latest.current), listChannels()]);
      if (mine !== seq.current) return;
      setItems(feed);
      setChannels(chans);
      setError(null);
    } catch (e) {
      if (mine === seq.current) setError(String(e));
    } finally {
      if (mine === seq.current) setLoading(false);
    }
  }, []);

  // Filter is a plain object rebuilt each render; compare by value.
  const key = JSON.stringify(filter);
  useEffect(() => {
    void reload();
  }, [key, reload]);

  return { items, channels, loading, error, reload };
}
