"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useSite } from "@/lib/site-context";
import { useModule } from "@/lib/modules";

type Page = { slug: string; title: string };

/**
 * Links to the site's static pages.
 *
 * Terms, privacy and the rest existed and were reachable only by typing the
 * URL — there was nothing anywhere on the site linking to them.
 */
export function SiteFooter() {
  const { siteName } = useSite();
  const [pages, setPages] = useState<Page[]>([]);
  const contactOn = useModule("contact");
  const supportOn = useModule("support");

  useEffect(() => {
    fetch("/api/pages")
      .then((r) => (r.ok ? r.json() : []))
      .then((d) => setPages(Array.isArray(d) ? d : []))
      .catch(() => {});
  }, []);

  if (pages.length === 0 && !contactOn && !supportOn) return null;

  return (
    <footer className="site-footer">
      {pages.map((p) => (
        <Link key={p.slug} href={`/pages/${p.slug}`}>
          {p.title}
        </Link>
      ))}

      {contactOn && <Link href="/contact">Contact</Link>}
      {supportOn && <Link href="/support">Support</Link>}
      <span className="site-footer-mark">
        © {new Date().getFullYear()} {siteName}
      </span>
    </footer>
  );
}
