// The Ampelos section of the sticknife-wide profile.
//
// accounts.sticknife.com iframes this into its own collapsible panel:
//
//   <iframe src="https://ampelos.sticknife.com/embed/profile"
//           title="Ampelos" loading="lazy"></iframe>
//
// WHY THE COOKIE REACHES US. accounts.sticknife.com and ampelos.sticknife.com
// share the registrable domain sticknife.com, so a request from one to the
// other is SAME-SITE even though it is cross-origin. The NextAuth session
// cookie is SameSite=Lax, which is sent on same-site subresource loads -- so
// the person is simply signed in inside the frame, with no token exchange, no
// shared secret, and no cookie loosened to SameSite=None. This holds only while
// both services live under sticknife.com; moving either to its own domain
// breaks it and would need a real token flow instead.
//
// WHY IT DOES NOT REDIRECT TO /login. /embed is exempted from the proxy's login
// redirect on purpose. Authentik refuses to be framed, so redirecting would
// render an X-Frame-Options error inside charon's panel -- a broken-looking box
// with no explanation. A signed-out visitor gets a sign-in link that escapes
// the frame instead.

import Link from "next/link";

import { auth } from "@/auth";
import { APP_URL } from "@/lib/app-url";
import { getProfile } from "@/lib/profile";

import { ProfilePanel } from "../../profile/profile-panel";

export const dynamic = "force-dynamic";

function Shell({ children }: { children: React.ReactNode }) {
  return <div className="p-4">{children}</div>;
}

export default async function EmbeddedProfilePage() {
  const session = await auth();

  if (!session?.user?.id) {
    return (
      <Shell>
        <div className="space-y-3">
          <p className="text-sm text-ampelos-muted">
            You are not signed in to Ampelos.
          </p>
          <Link
            href={`${APP_URL}/profile`}
            target="_top"
            className="ampelos-stone-button inline-block px-4 py-2 text-sm font-medium"
          >
            Sign in to Ampelos
          </Link>
        </div>
      </Shell>
    );
  }

  const profile = await getProfile(session.user.id, APP_URL);

  // Signed in to Authentik but with no Ampelos user row. Rare, and worth saying
  // plainly rather than showing an empty panel that reads as "you have nothing".
  if (!profile) {
    return (
      <Shell>
        <p className="text-sm text-ampelos-muted">
          This account has no Ampelos profile yet. Visit{" "}
          <Link href={`${APP_URL}/`} target="_top" className="text-ampelos-gold hover:underline">
            ampelos.sticknife.com
          </Link>{" "}
          once to create one.
        </p>
      </Shell>
    );
  }

  return (
    <Shell>
      <ProfilePanel profile={profile} embedded />
    </Shell>
  );
}
