import fs from "fs";
import path from "path";

export default async function FilePage({
  params,
}: {
  params: Promise<{ path?: string[] }>;
}) {
  const { path: segments = [] } = await params;   // <-- FIXED
  const filePath = segments.join("/") || "";

  // Resolve to actual file in /public
  const fullPath = path.join(process.cwd(), "public", filePath);

  // 404
  if (!fs.existsSync(fullPath)) {
    return (
      <div className="p-6 font-mono text-red-400">
        404 - File not found: /{filePath}
      </div>
    );
  }

  // Directory → list contents
  if (fs.lstatSync(fullPath).isDirectory()) {
    const files = fs.readdirSync(fullPath);

    return (
      <div className="p-6 font-mono text-green-400">
        <h2 className="mb-4 text-xl font-bold text-zinc-200">/{filePath}</h2>
        {files.map((name) => (
          <div key={name}>- {name}</div>
        ))}
      </div>
    );
  }

  // File → read contents
  const content = fs.readFileSync(fullPath, "utf8");

  return (
    <div className="p-6 font-mono text-green-400 whitespace-pre-wrap">
      <h2 className="mb-4 text-xl font-bold text-zinc-200">/{filePath}</h2>
      {content}
    </div>
  );
}
