import { useCallback, useEffect, 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);

  const reload = useCallback(async () => {
    setLoading(true);
    try {
      const [feed, chans] = await Promise.all([listFeed(filter), listChannels()]);
      setItems(feed);
      setChannels(chans);
      setError(null);
    } catch (e) {
      setError(String(e));
    } finally {
      setLoading(false);
    }
    // Filter is a plain object rebuilt each render; compare by value.
  }, [JSON.stringify(filter)]);

  useEffect(() => {
    reload();
  }, [reload]);

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