import { ImageResponse } from "next/og";
import fs from "node:fs";
import path from "node:path";
import { site } from "@/content/site";

// Shared Open Graph canvas size (1.91:1). Each opengraph-image route re-exports
// this as its `size` config so the whole system stays a single source of truth.
export const OG_SIZE = { width: 1200, height: 630 };

// Website Color System: Strictly Black #0A0A0A + White #FFFFFF + Neutral Grayscale
const BG = "#0a0a0a";
const TEXT_MUTED = "#a1a1aa";

// Load brand font (Fraunces Bold) for server-side Satori rendering (§29, §35)
let frauncesFontBuffer: Buffer | null = null;
try {
  const fontPath = path.join(process.cwd(), "lib/fonts/Fraunces-Bold.ttf");
  if (fs.existsSync(fontPath)) {
    frauncesFontBuffer = fs.readFileSync(fontPath);
  }
} catch {
  frauncesFontBuffer = null;
}

// Load official bot logo as base64 data URL for Satori embedding (§27, §36)
let botLogoDataUrl = "";
try {
  const botPath = path.join(process.cwd(), "public/images/quto-logo.png");
  if (fs.existsSync(botPath)) {
    const buf = fs.readFileSync(botPath);
    botLogoDataUrl = `data:image/png;base64,${buf.toString("base64")}`;
  }
} catch {
  botLogoDataUrl = "";
}

// Consistent brand descriptor beneath every headline
const BRAND_SUB =
  "Done-for-you conversational agents that book, qualify and support your customers.";

/**
 * Reusable Open Graph card for the whole site.
 *
 * Renders the official Quto AI brand frame:
 * - Combined logo: [Colorful Bot Icon] + Quto AI (in Fraunces luxury serif)
 * - Dynamic page title (in Fraunces, size-clamped)
 * - Eyebrow category badge (in crisp monochrome pill)
 * - Brand descriptor
 * - Footer with omni-channel indicators & domain
 * - Subtle monochrome radial glow on pure #0A0A0A ground
 */
export function ogImage({
  title,
  eyebrow,
}: {
  title: string;
  eyebrow?: string;
}): ImageResponse {
  // Clamp the headline font size so long titles wrap cleanly within the 1200x630 card
  const len = title.length;
  const titleFontSize =
    len > 85 ? 46 : len > 65 ? 52 : len > 45 ? 60 : len > 30 ? 68 : 74;

  const fontConfig = frauncesFontBuffer
    ? [
        {
          name: "Fraunces",
          data: frauncesFontBuffer,
          style: "normal" as const,
          weight: 700 as const,
        },
      ]
    : undefined;

  return new ImageResponse(
    (
      <div
        style={{
          width: "100%",
          height: "100%",
          display: "flex",
          flexDirection: "column",
          justifyContent: "space-between",
          padding: "72px 80px",
          background: BG,
          color: "#ffffff",
          fontFamily: frauncesFontBuffer ? "Fraunces, serif" : "serif",
          position: "relative",
          overflow: "hidden",
        }}
      >
        {/* Subtle monochrome ambient glow, top-right */}
        <div
          style={{
            position: "absolute",
            top: "-180px",
            right: "-120px",
            width: "580px",
            height: "580px",
            borderRadius: "9999px",
            background:
              "radial-gradient(circle, rgba(255, 255, 255, 0.08) 0%, rgba(10, 10, 10, 0) 70%)",
            display: "flex",
          }}
        />

        {/* Top Header: Official Combined Logo [Colorful Bot Icon] + [Quto AI] */}
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            width: "100%",
          }}
        >
          <div style={{ display: "flex", alignItems: "center", gap: "16px" }}>
            {botLogoDataUrl ? (
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  width: "52px",
                  height: "52px",
                }}
              >
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src={botLogoDataUrl}
                  alt="Quto AI Bot"
                  width={50}
                  height={50}
                  style={{ objectFit: "contain" }}
                />
              </div>
            ) : null}
            <span
              style={{
                fontSize: "42px",
                fontWeight: 700,
                letterSpacing: "-0.02em",
                color: "#ffffff",
              }}
            >
              {site.name}
            </span>
          </div>

          {eyebrow ? (
            <div
              style={{
                display: "flex",
                alignItems: "center",
                padding: "8px 20px",
                borderRadius: "9999px",
                border: "1px solid rgba(255, 255, 255, 0.20)",
                background: "rgba(255, 255, 255, 0.06)",
              }}
            >
              <span
                style={{
                  fontSize: "20px",
                  fontWeight: 600,
                  color: "#ffffff",
                  letterSpacing: "0.08em",
                  textTransform: "uppercase",
                }}
              >
                {eyebrow}
              </span>
            </div>
          ) : (
            <div
              style={{
                display: "flex",
                alignItems: "center",
                padding: "8px 20px",
                borderRadius: "9999px",
                border: "1px solid rgba(255, 255, 255, 0.20)",
                background: "rgba(255, 255, 255, 0.06)",
              }}
            >
              <span
                style={{
                  fontSize: "20px",
                  fontWeight: 600,
                  color: "#ffffff",
                  letterSpacing: "0.08em",
                  textTransform: "uppercase",
                }}
              >
                Enterprise AI
              </span>
            </div>
          )}
        </div>

        {/* Middle Section: Dynamic Title + Brand Sub */}
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            maxWidth: "1020px",
          }}
        >
          <span
            style={{
              fontSize: `${titleFontSize}px`,
              fontWeight: 700,
              lineHeight: 1.1,
              letterSpacing: "-0.025em",
              color: "#ffffff",
            }}
          >
            {title}
          </span>
          <span
            style={{
              fontSize: "26px",
              color: TEXT_MUTED,
              marginTop: "22px",
              lineHeight: 1.4,
              fontFamily: "sans-serif",
            }}
          >
            {BRAND_SUB}
          </span>
        </div>

        {/* Footer: Omni-channel tags + domain in monochrome */}
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            borderTop: "1px solid rgba(255, 255, 255, 0.12)",
            paddingTop: "24px",
          }}
        >
          <div style={{ display: "flex", alignItems: "center", gap: "10px" }}>
            <div
              style={{
                width: "8px",
                height: "8px",
                borderRadius: "9999px",
                background: "#ffffff",
                display: "flex",
              }}
            />
            <span
              style={{
                fontSize: "24px",
                color: "#d4d4d8",
                fontFamily: "sans-serif",
              }}
            >
              Voice · WhatsApp · Web · Chat
            </span>
          </div>
          <span
            style={{
              fontSize: "26px",
              color: "#ffffff",
              fontWeight: 700,
              fontFamily: "sans-serif",
            }}
          >
            {site.domain}
          </span>
        </div>
      </div>
    ),
    {
      ...OG_SIZE,
      fonts: fontConfig,
    },
  );
}
