import { readApps, type AppEntry } from "@/lib/registry";
import { currentUser } from "@/lib/serverAuth";
import { access } from "@/lib/users";

// Always render the current registry (it changes at runtime via the admin).
export const dynamic = "force-dynamic";

export default async function HubPage() {
  const all = await readApps();
  const user = await currentUser();
  // Show only the apps this user may access (admins / "*" see all).
  const acc = user ? await access(user.email) : { all: false, apps: [] as string[] };
  const apps = acc.all ? all : all.filter((a) => acc.apps.includes(a.slug));

  return (
    <>
      <h1 className="page-title">Proof of Concepts</h1>
      <p className="page-sub">Digt POC apps you can access. Pick one to open it.</p>

      {apps.length === 0 ? (
        <div className="empty">
          {all.length === 0
            ? <>No apps registered yet. Add one under <strong>Admin</strong>.</>
            : <>No apps are assigned to your account yet — ask an admin to grant access.</>}
        </div>
      ) : (
        <div className="grid">
          {apps.map((a) => (
            <AppCard key={a.slug} app={a} />
          ))}
        </div>
      )}
    </>
  );
}

function AppCard({ app }: { app: AppEntry }) {
  const openable = app.status !== "offline";
  const inner = (
    <>
      <span className={`badge ${app.status}`}>{app.status}</span>
      <h3>{app.title}</h3>
      <p>{app.description}</p>
      <span className="path">{app.path}</span>
    </>
  );
  // Cards link to a sibling app's own path at the domain root (not a hub-internal
  // route), so the registry `path` is used as-is.
  return openable ? (
    <a className="card link" href={app.path}>{inner}</a>
  ) : (
    <div className="card">{inner}</div>
  );
}
