import { useState, useEffect } from "react";
import { s as supabase } from "./client-Dz5aErML.js";
function buildProducts(rows, pkgs, images) {
  return rows.map((r) => ({
    id: r.id,
    name: r.name,
    game: r.game,
    price: r.price,
    status: r.status,
    description: r.description,
    image: r.image_url ?? void 0,
    createdAt: new Date(r.created_at).getTime(),
    readyEstimateAt: r.ready_estimate_at,
    whatsappNumber: r.whatsapp_number,
    whatsappChannelUrl: r.whatsapp_channel_url,
    rentalPackages: pkgs.filter((p) => p.product_id === r.id).sort((a, b) => a.sort_order - b.sort_order).map((p) => ({ id: p.id, duration: p.duration, price: p.price })),
    gallery: images.filter((i) => i.product_id === r.id).sort((a, b) => a.sort_order - b.sort_order).map((i) => i.image_url)
  }));
}
function useProducts() {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const refetch = async () => {
    const [{ data: prods }, { data: pkgs }, { data: imgs }] = await Promise.all([
      supabase.from("products").select("*").order("sort_order", { ascending: true }).order("created_at", { ascending: false }),
      supabase.from("rental_packages").select("*"),
      supabase.from("product_images").select("*")
    ]);
    setProducts(
      buildProducts(
        prods ?? [],
        pkgs ?? [],
        imgs ?? []
      )
    );
    setLoading(false);
  };
  useEffect(() => {
    refetch();
    const channelId = `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
    const channelName = `products-realtime-${channelId}`;
    const channel = supabase.channel(channelName);
    channel.on("postgres_changes", { event: "*", schema: "public", table: "products" }, () => {
      refetch();
    }).on("postgres_changes", { event: "*", schema: "public", table: "rental_packages" }, () => {
      refetch();
    }).on("postgres_changes", { event: "*", schema: "public", table: "site_settings" }, () => {
      refetch();
    }).subscribe();
    return () => {
      supabase.removeChannel(channel);
    };
  }, []);
  return { products, loading, refetch };
}
export {
  useProducts as u
};
