// ModuFoodService — root app
// Products are loaded live from Supabase (kept in sync with the admin panel).
const SUPABASE_URL = "https://ctykufoyfzhufkguuxcb.supabase.co";
const SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImN0eWt1Zm95ZnpodWZrZ3V1eGNiIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzM4MzY4NDksImV4cCI6MjA4OTQxMjg0OX0.YjEX-agq9rXjoXhIS9QuP3_roel08LGUa1Adl3-lhl0";
const sb = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);

// Map a Supabase row to the shape the views render.
function mapProduct(r) {
  return {
    id: r.id,
    sku: r.sku || r.pid || "—",
    pid: r.pid || "",
    name: r.name || "",
    name_ko: r.name_ko || "",
    category: r.category || "Uncategorized",
    price: r.price,
    badge: r.badge || "",
    note: r.description || "",
    note_ko: r.description_ko || "",
    image: r.image_url || "",
    featured: !!r.is_featured,
  };
}

const VIEWS = ["home", "products", "services", "about", "locations"];
function viewFromHash() {
  const h = (window.location.hash || "").replace(/^#/, "");
  return VIEWS.includes(h) ? h : "home";
}

function App() {
  const [view, setView] = React.useState(viewFromHash());
  const [product, setProduct] = React.useState(null);
  const [lang, setLang] = React.useState("en");

  const [products, setProducts] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);

  const T = window.MFS_I18N[lang];

  // Load products once from Supabase.
  React.useEffect(() => {
    let alive = true;
    (async () => {
      const { data, error } = await sb
        .from("products")
        .select("*")
        .or("visibility.eq.public,visibility.is.null")
        .order("is_featured", { ascending: false })
        .order("created_at", { ascending: false });
      if (!alive) return;
      if (error) {
        setError(error.message);
        setProducts([]);
      } else {
        setProducts((data || []).map(mapProduct));
      }
      setLoading(false);
    })();
    return () => { alive = false; };
  }, []);

  // Sync active view when the URL hash changes (deep links / old-page redirects).
  React.useEffect(() => {
    function onHash() {
      setView(viewFromHash());
      setProduct(null);
      document.body.style.overflow = "";
    }
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  function pick(p) {
    setProduct(p);
    document.body.style.overflow = "hidden";
  }
  function closeDrawer() {
    setProduct(null);
    document.body.style.overflow = "";
  }

  function nav(next) {
    setView(next);
    setProduct(null);
    document.body.style.overflow = "";
    if (next === "home") {
      history.replaceState(null, "", window.location.pathname + window.location.search);
    } else {
      window.location.hash = next;
    }
  }

  // Derived facets from the live catalog.
  const categories = React.useMemo(
    () => [...new Set(products.map((p) => p.category).filter(Boolean))].sort(),
    [products]
  );
  const badges = React.useMemo(
    () => [...new Set(products.map((p) => p.badge).filter(Boolean))].sort(),
    [products]
  );

  const catalog = { products, categories, badges, loading, error };

  let current;
  if (view === "home") current = <HomeView setView={nav} onPick={pick} catalog={catalog} lang={lang} T={T} />;
  else if (view === "products") current = <CatalogView onPick={pick} catalog={catalog} lang={lang} T={T} />;
  else if (view === "services") current = <ServicesView setView={nav} lang={lang} T={T} />;
  else if (view === "about") current = <AboutView setView={nav} lang={lang} T={T} />;
  else if (view === "locations") current = <LocationsView setView={nav} lang={lang} T={T} />;

  return (
    <div data-screen-label={"MFS · " + view}>
      <Topbar view={view} setView={nav} lang={lang} setLang={setLang} T={T} />
      {current}
      <Footer setView={nav} lang={lang} T={T} />
      <ProductDrawer product={product} onClose={closeDrawer} lang={lang} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
