"use client";

/**
 * The article list on /thought-leadership-articles (API reference: "How articles work
 * (website)"). Same markup and classes as the design; the tabs come from
 * GET /public/article-categories, the cards and pagination from GET /public/articles.
 *
 * - The server renders the first page of "All" (`initial`), so the page stays static.
 *   The selected tab and page live in the URL (?category=ai-supply-chain&page=2) so they
 *   can be shared; the browser fetches the matching cards through /api/v1.
 * - Until the API has a published article (or when it can't be reached) the designed
 *   placeholder list is shown instead (StaticArticles).
 * - A tab with no articles shows the section's noResultsText; without that text such
 *   tabs are hidden.
 */
import { useEffect, useMemo, useRef, useState, useSyncExternalStore, type MouseEvent } from "react";
import { normalizeContent } from "@/app/(site)/_lib/content";
import { ARTICLES_PER_PAGE, pageList, type ArticleCategoryList, type ArticleList } from "@/app/(site)/_lib/articles";
import type { ArticleListingContent } from "@/app/(site)/_lib/pageContent";
import { spaced } from "../pages/parts";
import { Chevron, FilterBar, StaticArticles } from "../pages/thought-leadership-articles/StaticArticles";
import { ArticleCardItem } from "./ArticleCardItem";

const LANG = "en";

/* The page URL's query string holds the tab and page (shareable links). */
const urlListeners = new Set<() => void>();
function subscribeUrl(cb: () => void) {
  urlListeners.add(cb);
  addEventListener("popstate", cb);
  return () => {
    urlListeners.delete(cb);
    removeEventListener("popstate", cb);
  };
}
const urlSearch = () => window.location.search;
/** On the server (and while hydrating): "All", page 1. */
const serverSearch = () => "";

function readUrl(search: string) {
  const p = new URLSearchParams(search);
  const page = Number(p.get("page"));
  return { category: p.get("category")?.trim() ?? "", page: Number.isInteger(page) && page > 1 ? page : 1 };
}
function writeUrl(category: string, page: number) {
  const p = new URLSearchParams(window.location.search);
  if (category) p.set("category", category);
  else p.delete("category");
  if (page > 1) p.set("page", String(page));
  else p.delete("page");
  const qs = p.toString();
  window.history.pushState(window.history.state, "", `${window.location.pathname}${qs ? `?${qs}` : ""}`);
  urlListeners.forEach((l) => l());
}

const listQuery = (category: string, page: number) => `limit=${ARTICLES_PER_PAGE}&page=${page}${category ? `&category=${encodeURIComponent(category)}` : ""}`;

async function getData<T>(path: string, signal: AbortSignal): Promise<T> {
  const res = await fetch(`/api/v1${path}`, { signal, headers: { Accept: "application/json" } });
  if (!res.ok) throw new Error(String(res.status));
  return normalizeContent(((await res.json()) as { data: T }).data);
}

type Props = {
  c: ArticleListingContent;
  /** First page of "All" and the tabs, from the server (null: the API couldn't be reached). Undefined: load them here (admin preview). */
  initial?: { list: ArticleList | null; categories: ArticleCategoryList | null };
};

export function ArticleListing({ c, initial }: Props) {
  const { category, page } = readUrl(useSyncExternalStore(subscribeUrl, urlSearch, serverSearch));
  const query = listQuery(category, page);
  const firstQuery = listQuery("", 1);
  const [lists, setLists] = useState<{ byQuery: Record<string, ArticleList>; failed: Record<string, true>; latest?: ArticleList }>(() =>
    initial?.list ? { byQuery: { [firstQuery]: initial.list }, failed: {} } : { byQuery: {}, failed: {} },
  );
  const [categories, setCategories] = useState<ArticleCategoryList | null | undefined>(initial ? initial.categories : undefined);
  const loading = !(query in lists.byQuery) && !(query in lists.failed);
  const data = lists.byQuery[query] ?? (loading ? lists.latest : undefined);
  // The list exists once the API has at least one article (then an empty tab is shown as such).
  const exists = useMemo(() => (categories?.total ?? 0) > 0 || Object.values(lists.byQuery).some((l) => l.total > 0), [categories, lists.byQuery]);
  const sectionRef = useRef<HTMLElement>(null);

  // Cards for the URL's tab and page (the server's first page needs no fetch).
  useEffect(() => {
    if (!loading) return;
    // With the server's answer saying "no articles", don't fetch filtered pages either.
    if (initial && !exists) return;
    const ctl = new AbortController();
    getData<ArticleList>(`/public/articles?lang=${LANG}&${query}`, ctl.signal)
      .then((next) => setLists((r) => ({ ...r, byQuery: { ...r.byQuery, [query]: next }, latest: next })))
      .catch((e: Error) => {
        if (e.name === "AbortError") return;
        console.warn("[articles] could not load articles:", e);
        setLists((r) => ({ ...r, failed: { ...r.failed, [query]: true } }));
      });
    return () => ctl.abort();
  }, [query, loading, initial, exists]);

  // Tabs (admin preview only: the website page gets them from the server).
  useEffect(() => {
    if (categories !== undefined) return;
    const ctl = new AbortController();
    getData<ArticleCategoryList>(`/public/article-categories?lang=${LANG}`, ctl.signal)
      .then(setCategories)
      .catch((e: Error) => e.name !== "AbortError" && setCategories(null));
    return () => ctl.abort();
  }, [categories]);

  if (!exists) return <StaticArticles c={c} />;

  const go = (nextCategory: string, nextPage: number) => {
    writeUrl(nextCategory, nextPage);
    const top = sectionRef.current?.getBoundingClientRect().top;
    if (top !== undefined && top < 0) sectionRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
  };
  const onCategory = (slug: string, e: MouseEvent) => {
    if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;
    e.preventDefault();
    go(slug, 1);
  };

  const tabs = (categories?.items ?? []).filter((t) => t.count > 0 || !!c.noResultsText || t.slug === category);
  const items = data?.items ?? [];
  const totalPages = data?.totalPages ?? 0;
  const empty = !loading && items.length === 0;

  return (
    <>
      <FilterBar>
        {spaced([
          <button key="all" type="button" className={`articles-filter-pill${category ? "" : " is-active"}`} role="tab" aria-selected={!category} onClick={() => go("", 1)}>
            {c.allFilterLabel}
          </button>,
          ...tabs.map((t) => (
            <button key={t.slug} type="button" className={`articles-filter-pill${t.slug === category ? " is-active" : ""}`} role="tab" aria-selected={t.slug === category} onClick={() => go(t.slug, 1)}>
              {t.name}
            </button>
          )),
        ])}
      </FilterBar>
      <section ref={sectionRef} className="articles-section scroll-mt-28" aria-labelledby="articles-heading" aria-busy={loading}>
        <div className="w-full max-w-[1180px] mx-auto px-6">
          <h2 id="articles-heading" className="sr-only">
            {c.heading}
          </h2>
          {empty ? (
            c.noResultsText ? <p className="py-12 text-center text-[15px] leading-[1.7] text-[#4A4A4A]">{c.noResultsText}</p> : null
          ) : (
            <div className={`articles-grid transition-opacity duration-200${loading ? " opacity-60" : ""}`}>
              {items.map((a) => (
                <ArticleCardItem key={a.slug} a={a} onCategory={onCategory} />
              ))}
            </div>
          )}
          {totalPages > 1 && (
            <nav className="pagination mt-12 mb-4 flex items-center justify-center gap-2 flex-wrap" aria-label="Article pages">
              {spaced([
                <button key="prev" type="button" className="pagination-btn pagination-arrow" aria-label="Previous page" disabled={page <= 1} onClick={() => go(category, page - 1)}>
                  <Chevron d={["M10 3L5 8l5 5", "M12 3L7 8l5 5"]} />
                </button>,
                ...pageList(page, totalPages).map((p, i) =>
                  p === null ? (
                    <span key={`gap${i}`} className="pagination-ellipsis text-[#2E2E2E] px-1 select-none" aria-hidden="true">
                      …
                    </span>
                  ) : (
                    <button
                      key={p}
                      type="button"
                      className={`pagination-btn${p === page ? " is-active" : ""}`}
                      aria-current={p === page ? "page" : undefined}
                      aria-label={`Page ${p}`}
                      onClick={() => p !== page && go(category, p)}
                    >
                      {p}
                    </button>
                  ),
                ),
                <button key="next" type="button" className="pagination-btn pagination-arrow" aria-label="Next page" disabled={page >= totalPages} onClick={() => go(category, page + 1)}>
                  <Chevron d={["M6 3l5 5-5 5", "M4 3l5 5-5 5"]} />
                </button>,
              ])}
            </nav>
          )}
        </div>
      </section>
    </>
  );
}
