import Link from "next/link";
import path from "path";
import { promises as fs } from "fs";

const APP_DIR = path.join(process.cwd(), "app");

async function collectRoutes(rootDir: string): Promise<string[]> {
  const routes: string[] = [];

  async function walk(relativeDir: string) {
    const absoluteDir = path.join(rootDir, relativeDir);
    const entries = await fs.readdir(absoluteDir, { withFileTypes: true });
    const names = entries.map((e) => e.name);

    if (names.includes("page.tsx")) {
      const routePath =
        relativeDir === "" ? "/" : `/${relativeDir.replace(/\\\\/g, "/")}`;
      routes.push(routePath);
    }

    for (const entry of entries) {
      if (!entry.isDirectory()) continue;
      if (["api", "components"].includes(entry.name)) continue;
      if (entry.name.startsWith("(")) continue;
      if (entry.name.startsWith("_")) continue;
      if (entry.name === "node_modules") continue;

      await walk(path.join(relativeDir, entry.name));
    }
  }

  await walk("");

  routes.sort((a, b) => {
    if (a === "/" && b !== "/") return -1;
    if (b === "/" && a !== "/") return 1;
    return a.localeCompare(b);
  });

  return routes;
}

export default async function Pages() {
  const routes = await collectRoutes(APP_DIR);

  return (
    <main style={{ maxWidth: 800, margin: "0 auto", padding: "24px" }}>
      <h1 style={{ fontSize: 24, fontWeight: 700, marginBottom: 16 }}>
        모든 페이지 링크
      </h1>
      <ul style={{ display: "grid", gap: 8, listStyle: "none", padding: 0 }}>
        {routes.map((route) => (
          <li key={route}>
            <Link href={route} style={{ color: "#2563eb" }}>
              {route}
            </Link>
          </li>
        ))}
      </ul>
    </main>
  );
}


