"use client";

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

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

/**
 * The links that sit at the foot of the right-hand column: the site's own
 * pages, a way to get in touch, and the language.
 */
export function RailFooter() {
  const { siteName } = useSite();

  const [pages, setPages] = useState<Page[]>([]);
  const [languages, setLanguages] = useState<{ code: string; label: string }[]>([]);
  const [current, setCurrent] = useState("en");

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

    fetch("/api/locale")
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => {
        if (d?.languages) setLanguages(d.languages);
        if (d?.language) setCurrent(d.language);
      })
      .catch(() => {});
  }, []);

  useEffect(load, [load]);

  return (
    <div className="rf-card">
      <p className="rf-copy">
        © {new Date().getFullYear()} {siteName}
      </p>

      <nav className="rf-links">
        {pages.map((p) => (
          <Link key={p.slug} href={`/p/${p.slug}`}>
            {p.title}
          </Link>
        ))}

        <Link href="/support">Support</Link>
      </nav>

      {languages.length > 1 && (
        <div className="rf-langs">
          {languages.slice(0, 4).map((l) => (
            <button
              key={l.code}
              onClick={() => {
                setCurrent(l.code);
                // The choice is remembered by the locale endpoint.
                fetch("/api/locale", {
                  method: "POST",
                  headers: { "Content-Type": "application/json" },
                  body: JSON.stringify({ language: l.code }),
                })
                  .then(() => location.reload())
                  .catch(() => {});
              }}
              className={clsx("rf-lang", current === l.code && "on")}
            >
              {current === l.code && <i />}
              {l.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
