import { ImageResponse } from "next/og";

export const dynamic = "force-dynamic";
export const revalidate = 0;
export const alt = "Sinss profile preview";
export const size = { width: 1200, height: 630 };
export const contentType = "image/png";
import { isAccountRestricted } from "@/lib/moderation";
import { normalizeUsernameRouteParam } from "@/lib/constants";

type ProfilePreview = {
  username: string;
  display_name: string | null;
  bio: string | null;
  avatar_url: string | null;
  website_title: string | null;
  website_description: string | null;
  website_image_url: string | null;
  accent: string | null;
  embed_preset: string | null;
  add_user_info_overlay: boolean | null;
  moderation_status: "active" | "suspended" | "banned" | null;
  suspended_until: string | null;
};

async function getProfile(usernameOrAlias: string): Promise<ProfilePreview | null> {
  const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
  const serviceRole = process.env.SUPABASE_SERVICE_ROLE_KEY;
  if (!supabaseUrl || !serviceRole) return null;

  const fields = "username,display_name,bio,avatar_url,website_title,website_description,website_image_url,accent,embed_preset,add_user_info_overlay,moderation_status,suspended_until";
  const headers = { apikey: serviceRole, Authorization: `Bearer ${serviceRole}` };

  for (const field of ["username", "alias"]) {
    const query = new URLSearchParams({ select: fields, [field]: `eq.${usernameOrAlias}`, limit: "1" });
    const response = await fetch(`${supabaseUrl}/rest/v1/profiles?${query}`, { headers, cache: "no-store" });
    if (!response.ok) return null;
    const profiles = (await response.json()) as ProfilePreview[];
    if (profiles[0]) {
      const profile = profiles[0];
      return isAccountRestricted(profile.moderation_status, profile.suspended_until) ? null : profile;
    }
  }

  return null;
}

export default async function OpenGraphImage({ params }: { params: Promise<{ username: string }> }) {
  const username = normalizeUsernameRouteParam((await params).username);
  const profile = await getProfile(username);
  if (!profile) return new Response("Profile not found", { status: 404 });

  const title = profile.website_title || profile.display_name || profile.username;
  const description = (profile.website_description || profile.bio || `@${profile.username} on sinss.lol`)
    .replace(/\s+/g, " ")
    .trim()
    .slice(0, 150);

  const safeImageUrl = [profile.website_image_url, profile.avatar_url]
    .map((url) => (url || "").trim())
    .find((url) => {
      try {
        const parsed = new URL(url);
        return parsed.protocol === "https:" || parsed.protocol === "http:";
      } catch {
        return false;
      }
    }) || null;

  const accent = profile.accent && /^#[\da-f]{6}$/i.test(profile.accent) ? profile.accent : "#f5caca";
  const preset = profile.embed_preset === "minimal" || profile.embed_preset === "banner" ? profile.embed_preset : "classic";

  // If user disabled overlay and provided an image, render their custom image full-bleed
  if (profile.add_user_info_overlay === false && safeImageUrl) {
    try {
      return new ImageResponse(
        (
          <div style={{ width: "100%", height: "100%", display: "flex", background: "#0a0f14" }}>
            <img src={safeImageUrl} alt="" width={1200} height={630} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
          </div>
        ),
        size
      );
    } catch {
      // fallback to standard card
    }
  }

  if (preset === "banner") {
    try {
      const bgUrl = safeImageUrl;
      return new ImageResponse(
        (
          <div style={{ width: "100%", height: "100%", display: "flex", position: "relative", background: "#0a0f14", color: "#ffffff", fontFamily: "Arial, sans-serif" }}>
            {bgUrl && (
              <img
                src={bgUrl}
                alt=""
                width={1200}
                height={630}
                style={{ position: "absolute", top: 0, left: 0, right: 0, bottom: 0, width: "100%", height: "100%", objectFit: "cover", opacity: 0.45 }}
              />
            )}
            <div style={{ position: "absolute", top: 0, left: 0, right: 0, bottom: 0, display: "flex", background: "linear-gradient(180deg, rgba(0,0,0,0) 30%, rgba(7,10,14,0.92) 100%)" }} />
            <div style={{ position: "absolute", left: 48, bottom: 48, display: "flex", flexDirection: "column" }}>
              <div style={{ display: "flex", color: accent, fontSize: 22, fontWeight: 700 }}>@{profile.username}</div>
              <div style={{ display: "flex", fontSize: 64, fontWeight: 800, lineHeight: 1.1 }}>{title.slice(0, 30)}</div>
              <div style={{ display: "flex", color: "#5b0909", fontSize: 22, marginTop: 10 }}>{description.slice(0, 90)}</div>
              <div style={{ display: "flex", marginTop: 18, color: accent, fontWeight: 700, fontSize: 18 }}>sinss.lol/{profile.username}</div>
            </div>
          </div>
        ),
        size,
      );
    } catch (err) {
      console.error("Banner ImageResponse failed, falling back to classic:", err);
    }
  }

  if (preset === "minimal") {
    try {
      return new ImageResponse(
        (
          <div style={{ width: "100%", height: "100%", display: "flex", alignItems: "center", justifyContent: "center", background: "#740101", color: "#101418", fontFamily: "Arial, sans-serif" }}>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 14 }}>
              <div style={{ width: 96, height: 96, borderRadius: 48, overflow: "hidden", border: `3px solid ${accent}`, display: "flex", background: accent }}>
                {safeImageUrl ? <img src={safeImageUrl} alt="" width={96} height={96} style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : null}
              </div>
              <div style={{ display: "flex", fontSize: 52, fontWeight: 800 }}>{title.slice(0, 26)}</div>
              <div style={{ display: "flex", color: "#261010", fontSize: 22 }}>@{profile.username} | sinss.lol</div>
            </div>
          </div>
        ),
        size,
      );
    } catch (err) {
      console.error("Minimal ImageResponse failed, falling back to classic:", err);
    }
  }

  return new ImageResponse(
    (
      <div
        style={{
          width: "100%",
          height: "100%",
          display: "flex",
          padding: 38,
          background: "radial-gradient(circle at 82% 18%, rgba(245, 202, 202, 0.2), rgba(0,0,0,0) 32%), linear-gradient(135deg, #070a0e 0%, #111923 100%)",
          color: "#ffffff",
          fontFamily: "Arial, sans-serif",
        }}
      >
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            justifyContent: "space-between",
            width: "100%",
            border: "1px solid rgba(0, 0, 0, 0.14)",
            borderRadius: 28,
            padding: "32px 42px",
            background: "rgba(7,11,16,0.72)",
          }}
        >
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12, fontSize: 28, fontWeight: 800 }}>
              <div style={{ width: 12, height: 34, borderRadius: 8, background: accent }} />
              sinss.lol
            </div>
            <div
              style={{
                display: "flex",
                alignItems: "center",
                border: `1px solid ${accent}66`,
                borderRadius: 999,
                padding: "9px 16px",
                color: accent,
                fontSize: 15,
                fontWeight: 700,
              }}
            >
              Profile
            </div>
          </div>

          <div style={{ display: "flex", alignItems: "center", gap: 38, minHeight: 300 }}>
            {safeImageUrl ? (
              <img
                src={safeImageUrl}
                alt=""
                width={210}
                height={210}
                style={{ borderRadius: 105, objectFit: "cover", border: `4px solid ${accent}` }}
              />
            ) : (
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  width: 210,
                  height: 210,
                  borderRadius: 105,
                  border: `4px solid ${accent}`,
                  background: "#604a4a",
                  color: accent,
                  fontSize: 76,
                  fontWeight: 800,
                }}
              >
                {profile.username.slice(0, 1).toUpperCase()}
              </div>
            )}
            <div style={{ display: "flex", flexDirection: "column", justifyContent: "center", flex: 1, minWidth: 0 }}>
              <div style={{ display: "flex", color: accent, fontSize: 20, fontWeight: 700, marginBottom: 12 }}>
                @{profile.username}
              </div>
              <div style={{ display: "flex", fontSize: 54, lineHeight: 1.1, fontWeight: 800, overflow: "hidden" }}>
                {title.slice(0, 34)}
              </div>
              <div style={{ display: "flex", color: "#420909", fontSize: 22, lineHeight: 1.4, marginTop: 16, maxWidth: 760 }}>
                {description}
              </div>
            </div>
          </div>

          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              borderTop: "1px solid rgba(0, 0, 0, 0.12)",
              paddingTop: 18,
              color: "#400d0d",
              fontSize: 18,
            }}
          >
            <span>sinss.lol/{profile.username}</span>
            <span style={{ color: accent, fontWeight: 700 }}>Your space on the internet</span>
          </div>
        </div>
      </div>
    ),
    size
  );
}
