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

export default function FilePage({ params }: { params: { path?: string[] } }) {
  const filePath = params.path?.join("/") || "";

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

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

  // If it's a folder, list its 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>
    );
  }

  // Read file 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>
  );
}
