// Stories index screen for /pribehy/ (and language variants).
// Detail pages (/pribehy/<slug>/) are static HTML — no React there.

const { useState: useS, useMemo: useM } = React;

function StoriesScreen({ lang }) {
  const [filter, setFilter] = useS("all");

  // Sort/shuffle based on filter selection.
  // `name` is a {cs, vi, en} object — read the active-lang string before
  // calling localeCompare. Falls back to CS if a lang variant is missing.
  // (Earlier bug: sorting by the object stringified to "[object Object]" so
  // every comparison returned 0 and the order never changed.)
  const nameOf = (s) =>
    typeof s.name === "string" ? s.name : (s.name?.[lang] || s.name?.cs || "");

  const sorted = useM(() => {
    if (filter === "az") {
      return [...STORIES].sort((a, b) =>
        nameOf(a).localeCompare(nameOf(b), lang, { sensitivity: "base" })
      );
    }
    if (filter === "random") {
      const arr = [...STORIES];
      for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[j]] = [arr[j], arr[i]];
      }
      return arr;
    }
    return STORIES;
  }, [filter, lang]);

  const t = (key) => UI[key][lang];

  // Crumb home href: / for cs, /vi/ for vi, /en/ for en
  const homeHref = lang === "cs" ? "/" : `/${lang}/`;

  return (
    <main>
      <section className="container stories-hero">
        <div className="crumb">
          <a href={homeHref}>{t("crumbHome")}</a> / {t("crumbStories")}
        </div>
        <h1 dangerouslySetInnerHTML={{ __html: UI.storiesIndexTitleHTML[lang] }} />
        <p className="sub">{t("storiesIndexIntro")}</p>
      </section>

      <div className="container stories-toolbar">
        <div className="filters">
          {[
            { id: "all", labelKey: "filterAll" },
            { id: "az", labelKey: "filterAZ" },
            { id: "random", labelKey: "filterRandom" },
          ].map((f) => (
            <button
              key={f.id}
              className={filter === f.id ? "active" : ""}
              onClick={() => setFilter(f.id)}
            >
              {t(f.labelKey)}
            </button>
          ))}
        </div>
        <span className="count">{STORIES.length} {t("countSuffix")}</span>
      </div>

      <div className="container stories-full-grid">
        {sorted.map((s, i) => (
          <StoryCard key={s.slug} story={s} num={i + 1} lang={lang} />
        ))}
      </div>
    </main>
  );
}

Object.assign(window, { StoriesScreen });
