import { cookies } from "next/headers";
import { Metadata } from "next";
import ProfileClient from "./ProfileClient";
import { BASE_URL } from "@/components/main/BaseUrl";
import { User } from "@/types/types";
import { generatePageMetadata } from "@/utils/generatePageMetadata";
import { getServerLanguage } from "@/lib/i18n/server";
import { translateCommon } from "@/lib/i18n/translate";

export async function generateMetadata(): Promise<Metadata> {
  const lang = await getServerLanguage();
  const token = (await cookies()).get("token")?.value || "";
  const siteName = translateCommon(lang, "header.logoAlt");
  try {
    const res = await fetch(`${BASE_URL}/profile`, {
      cache: "no-store",
      headers: { Authorization: token ? `Bearer ${token}` : "" },
    });
    const data = await res.json();
    const user = data?.user as User;
    if (!user) {
      return generatePageMetadata({
        title: translateCommon(lang, "settings.profilePage.metaTitle"),
        description: translateCommon(lang, "settings.profilePage.metaDescription"),
        path: "/settings/profile",
        lang,
      });
    }
    const fullName = `${user.first_name || ""} ${user.last_name || ""}`.trim();
    const expertise = user.expertise || "";
    const city = user.city?.name || "";
    const bio = user.bio || "";
    const username = user.user_name || "";

    const title = [username, fullName, expertise, city, siteName]
      .filter(Boolean)
      .join(" – ");
    const description = [fullName, expertise, bio].filter(Boolean).join(" – ");

    return generatePageMetadata({
      title,
      description,
      path: "/settings/profile",
      type: "profile",
      lang,
    });
  } catch {
    return generatePageMetadata({
      title: translateCommon(lang, "settings.profilePage.metaTitle"),
      description: translateCommon(lang, "settings.profilePage.metaDescription"),
      path: "/settings/profile",
      lang,
    });
  }
}

export default function ProfilePage() {
  return <ProfileClient />;
}
