// Category — overview grid of 8 categories. Each card is a real cover from
// the latest case in that category and links to /category/?cat=<k> which
// renders the filtered case list view below.

const CAT_DESC = {
  "凶杀": "连环、悬案、无动机与不合逻辑的谋杀。",
  "UFO":  "目击、雷达数据、地面痕迹与电磁异常。",
  "灵异": "超自然现象、反复出现的异象与集体目击。",
  "邪教": "团体信仰、仪式、自愿者与内部档案。",
  "失踪": "无出口、无动机、无痕迹的失踪案件。",
  "传说": "口头相传、周期性、跨城市的民间叙事。",
  "禁地": "封闭区域、军用遗址、异常观测点。",
  "阴谋": "跨国档案、数据空白、被抹除的时间。",
};

function latestInCat(k) {
  return CASES.find(c => c.cat === k) || null;
}

const CatCard = ({ c, i }) => {
  const latest = latestInCat(c.k);
  const unsolved = CASES.filter(x => x.cat === c.k && x.status === "未结").length;
  const rot = ((i % 4) - 1.5) * 0.15;
  return (
    <a href={`/category/?cat=${encodeURIComponent(c.k)}`} style={{
      display: "block", background: "#14110f", border: "1px solid #2a2620",
      position: "relative", transform: `rotate(${rot}deg)`,
      boxShadow: "0 2px 0 rgba(0,0,0,0.5), 0 20px 40px -20px rgba(0,0,0,0.8)",
      color: "inherit",
    }}>
      <div style={{
        position: "absolute", top: -22, left: 20,
        background: "#14110f", border: "1px solid #2a2620", borderBottom: "none",
        padding: "4px 14px 3px", fontSize: 10, letterSpacing: 2, color: "#a89b78",
        fontFamily: "'JetBrains Mono',monospace",
      }}>▸ 类别 {String(i+1).padStart(2,"0")}</div>
      <div style={{ position: "absolute", top: 14, right: 14, zIndex: 2 }}>
        <Stamp text={c.en} rot={-8} size={0.8} />
      </div>
      <CoverImage item={latest || { id: c.k, cat_en: c.en }} label={c.en} seed={i*17+3}
        variant={i%2===0 ? "kraft" : "dark"} />
      <div style={{ padding: "18px 22px 20px" }}>
        <div className="mono" style={{ fontSize: 10, letterSpacing: 2, color: "#6a6257", marginBottom: 6 }}>
          {latest ? `LATEST · ${latest.date || latest.id}` : "NO FILES YET"}
        </div>
        <h3 style={{
          fontFamily: "'Noto Serif SC',serif", fontSize: 26, fontWeight: 500,
          color: "#f4ecd8", letterSpacing: 1, marginBottom: 4,
        }}>{c.zh}</h3>
        <div className="type" style={{ fontSize: 12, color: "#8a6f49", letterSpacing: 1, marginBottom: 12, fontStyle: "italic" }}>
          {c.en}
        </div>
        <p style={{ fontSize: 14, lineHeight: 1.6, color: "#c9bda0", marginBottom: 16, textWrap: "pretty" }}>
          {CAT_DESC[c.k] || ""}
        </p>
        <div style={{
          borderTop: "1px dashed #2a2620", paddingTop: 12,
          display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 10,
          fontFamily: "'JetBrains Mono',monospace", fontSize: 11,
        }}>
          <div><div style={{ color: "#6a6257", fontSize: 9, letterSpacing: 1.5 }}>案卷</div><div style={{ color: "#e8e2d0", fontSize: 16 }}>{c.count}</div></div>
          <div><div style={{ color: "#6a6257", fontSize: 9, letterSpacing: 1.5 }}>未结</div><div style={{ color: "#a81515", fontSize: 16 }}>{unsolved}</div></div>
          <div><div style={{ color: "#6a6257", fontSize: 9, letterSpacing: 1.5 }}>最新</div><div style={{ color: "#a89b78", fontSize: 12, paddingTop: 4, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{latest ? latest.id : "—"}</div></div>
        </div>
        <div className="mono" style={{
          marginTop: 14, fontSize: 11, letterSpacing: 2, color: "#a81515",
          borderBottom: "1px solid #a81515", paddingBottom: 2, display: "inline-block",
        }}>进入该类 → OPEN</div>
      </div>
    </a>
  );
};

const CategoryIndex = () => (
  <>
    <section style={{
      padding: "36px 48px 16px",
      display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 40,
      alignItems: "end", borderBottom: "1px dashed #2a2620",
    }}>
      <div>
        <div className="mono" style={{ fontSize: 10, letterSpacing: 3, color: "#6a6257", marginBottom: 8 }}>
          ▸ SECTION / 分类索引
        </div>
        <h2 style={{
          fontFamily: "'Noto Serif SC',serif", fontSize: 48, fontWeight: 500,
          color: "#f4ecd8", letterSpacing: 2, lineHeight: 1.1, marginBottom: 10,
        }}>按性质分门归档</h2>
        <div className="type" style={{ fontSize: 14, color: "#a89b78", fontStyle: "italic" }}>
          Files filed by nature — and by the particular kind of not-knowing they induce.
        </div>
      </div>
      <div style={{
        fontSize: 14, color: "#c9bda0", lineHeight: 1.7, textWrap: "pretty",
        borderLeft: "2px solid #8b0000", paddingLeft: 16,
      }}>
        档案以八类收纳。点击任一类别进入该类全部案卷。数字显示该类别已归档数量与未结占比。
      </div>
    </section>
    <section style={{ padding: "40px 48px 24px" }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "56px 28px" }}>
        {CATEGORIES.filter(c => c.k !== "all").map((c, i) => <CatCard key={c.k} c={c} i={i} />)}
      </div>
    </section>
  </>
);

const CategoryFilteredList = ({ cat, onBack }) => {
  const meta = CATEGORIES.find(c => c.k === cat);
  const cases = CASES.filter(c => c.cat === cat)
    .sort((a, b) => (b.published_ts || 0) - (a.published_ts || 0));
  return (
    <>
      <section style={{
        padding: "36px 48px 16px",
        display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 40,
        alignItems: "end", borderBottom: "1px dashed #2a2620",
      }}>
        <div>
          <a href="/category/" onClick={e => { e.preventDefault(); onBack(); }}
             className="mono" style={{
            fontSize: 11, letterSpacing: 3, color: "#a89b78", marginBottom: 14,
            display: "inline-block",
          }}>← 返回全部分类 / ALL CATEGORIES</a>
          <h2 style={{
            fontFamily: "'Noto Serif SC',serif", fontSize: 44, fontWeight: 500,
            color: "#f4ecd8", letterSpacing: 2, lineHeight: 1.1, marginTop: 8, marginBottom: 10,
          }}>{meta ? meta.zh : cat}</h2>
          <div className="type" style={{ fontSize: 14, color: "#a89b78", fontStyle: "italic" }}>
            {meta ? meta.en : ""} · {CAT_DESC[cat] || ""}
          </div>
        </div>
        <div className="mono" style={{
          fontSize: 12, letterSpacing: 1, color: "#c9bda0", lineHeight: 1.9,
          borderLeft: "2px solid #8b0000", paddingLeft: 18,
        }}>
          该类案卷 · <span style={{ color: "#f4ecd8" }}>{cases.length}</span><br/>
          其中未结 · <span style={{ color: "#a81515" }}>{cases.filter(c => c.status === "未结").length}</span>
        </div>
      </section>
      <section style={{ padding: "40px 48px 60px" }}>
        {cases.length === 0 ? (
          <div style={{ color: "#6a6257", padding: 48, textAlign: "center", fontStyle: "italic" }}>
            该分类下暂无案卷。
          </div>
        ) : (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: "48px 28px", rowGap: 56 }}>
            {cases.map((item, i) => (
              <CaseCard key={item.id} item={item} rot={((i%3)-1)*0.1} />
            ))}
          </div>
        )}
      </section>
    </>
  );
};

const App = () => {
  useDataReady();
  const [cat, setCat] = React.useState(() => {
    const p = new URLSearchParams(location.search);
    return p.get("cat") || "";
  });
  // Keep URL in sync when filter changes so shared links work.
  React.useEffect(() => {
    const url = new URL(location.href);
    if (cat) url.searchParams.set("cat", cat); else url.searchParams.delete("cat");
    history.replaceState(null, "", url);
  }, [cat]);

  if (!window.DATA_READY) {
    return (<>
      <ClassifiedBar /><SiteHeader /><SiteNav current="CATEGORY" />
      <LoadingArchive />
      <SiteFooter />
    </>);
  }
  return (
    <>
      <ClassifiedBar /><SiteHeader /><SiteNav current="CATEGORY" />
      {cat ? <CategoryFilteredList cat={cat} onBack={() => setCat("")} />
           : <CategoryIndex />}
      <SiteFooter />
    </>
  );
};

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