// lib/og.tsx
// Branded 1200x630 social-share image generated with next/og (Satori). Shared by
// app/opengraph-image.tsx and app/twitter-image.tsx so the OG and Twitter cards
// are identical. Colors + type pairing follow DESIGN.md (brand red #dc0d15 on a
// white canvas; Montserrat display + Poppins body). The Teleton wordmark is
// inlined as a data URI (lib/og-assets.ts) because Satori cannot read public/ on
// Vercel's serverless filesystem.

import { ImageResponse } from "next/og";
import { LOGO_DATA_URI } from "@/lib/og-assets";

export const OG_SIZE = { width: 1200, height: 630 };
export const OG_ALT = "Rifa Teletón Perú. Tu ayuda también te ayuda a ti";

const RED = "#dc0d15";
const INK = "#111111";
const MUTED = "#666666";

type LoadedFont = { name: string; data: ArrayBuffer; weight: 400 | 700; style: "normal" };

// Satori needs raw font bytes. Pull them from Google Fonts at render time (the
// result is cached alongside the generated image). Returns null on any failure
// so the card still renders with a default font instead of throwing.
async function loadFont(family: string, weight: 400 | 700): Promise<LoadedFont | null> {
  try {
    const css = await (
      await fetch(
        `https://fonts.googleapis.com/css2?family=${encodeURIComponent(family)}:wght@${weight}`,
        { headers: { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)" } },
      )
    ).text();
    const url = css.match(/src:\s*url\(([^)]+)\)\s*format\(/)?.[1];
    if (!url) return null;
    const data = await (await fetch(url)).arrayBuffer();
    return { name: family, data, weight, style: "normal" };
  } catch {
    return null;
  }
}

export async function renderBrandOgImage(): Promise<ImageResponse> {
  const [montserrat, poppins] = await Promise.all([
    loadFont("Montserrat", 700),
    loadFont("Poppins", 400),
  ]);
  const fonts = [montserrat, poppins].filter((f): f is LoadedFont => f !== null);
  const display = montserrat ? "Montserrat" : poppins ? "Poppins" : "sans-serif";
  const body = poppins ? "Poppins" : display;

  return new ImageResponse(
    (
      <div
        style={{
          width: "100%",
          height: "100%",
          display: "flex",
          flexDirection: "column",
          backgroundColor: "#ffffff",
          fontFamily: body,
        }}
      >
        {/* brand-red spine across the top */}
        <div style={{ display: "flex", height: 12, backgroundColor: RED }} />
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            justifyContent: "space-between",
            flex: 1,
            padding: "74px 80px 72px",
          }}
        >
          <div style={{ display: "flex" }}>
            <img src={LOGO_DATA_URI} width={244} height={78} alt="Teletón" />
          </div>

          <div style={{ display: "flex", flexDirection: "column" }}>
            <div
              style={{
                display: "flex",
                color: RED,
                fontFamily: display,
                fontSize: 26,
                fontWeight: 700,
                letterSpacing: 3,
                marginBottom: 20,
              }}
            >
              RIFA OFICIAL TELETÓN
            </div>
            <div
              style={{
                display: "flex",
                color: INK,
                fontFamily: display,
                fontSize: 78,
                fontWeight: 700,
                lineHeight: 1.04,
                maxWidth: 950,
              }}
            >
              Tu ayuda también te ayuda a ti
            </div>
            <div
              style={{
                display: "flex",
                color: MUTED,
                fontSize: 31,
                marginTop: 26,
                maxWidth: 900,
              }}
            >
              Participa desde S/5. Premios reales, sorteo supervisado.
            </div>
          </div>

          <div style={{ display: "flex", alignItems: "center" }}>
            <div
              style={{
                display: "flex",
                backgroundColor: RED,
                color: "#ffffff",
                fontFamily: display,
                fontSize: 28,
                fontWeight: 700,
                padding: "20px 42px",
                borderRadius: 999,
              }}
            >
              Quiero participar
            </div>
          </div>
        </div>
      </div>
    ),
    {
      width: OG_SIZE.width,
      height: OG_SIZE.height,
      fonts: fonts.length
        ? fonts.map((f) => ({ name: f.name, data: f.data, weight: f.weight, style: f.style }))
        : undefined,
    },
  );
}
