import { ImageResponse } from 'next/og';
import { markDataUri } from '@/components/brand/mark';
import { site } from './site';

/**
 * Shared renderer for social cards and app icons (rendered at build time by ImageResponse).
 */

type FontWeight = 400 | 500 | 600 | 700 | 800 | 900;
type OgFont = { name: string; data: ArrayBuffer; weight: FontWeight; style: 'normal' };

/**
 * Fetch a Google font subset as TTF (Satori cannot read woff2). Returns null when offline so the
 * image still renders with the built-in fallback font instead of failing the build.
 */
async function loadGoogleFont(family: string, weight: FontWeight, text: string): Promise<OgFont | null> {
  const url = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(family)}:wght@${weight}&text=${encodeURIComponent(text)}`;
  try {
    const css = await (await fetch(url)).text();
    const src = /src: url\((.+?)\) format\('(?:opentype|truetype)'\)/.exec(css)?.[1];
    if (!src) return null;
    const response = await fetch(src);
    if (!response.ok) return null;
    return { name: family, data: await response.arrayBuffer(), weight, style: 'normal' };
  } catch (error) {
    console.warn(`[og] Could not load ${family} ${weight}; using the fallback font.`, error instanceof Error ? error.message : error);
    return null;
  }
}

const OG_COLORS = {
  base: '#070b1f',
  surface: '#0d1433',
  line: '#23306b',
  fg: '#f2f4ff',
  muted: '#a9b1d6',
  violet: '#7c5cff',
  violetSoft: '#a996ff',
  cyan: '#22d3ee',
  amber: '#ffb020',
} as const;

export const ogSize = { width: 1200, height: 630 };
export const ogAlt = `${site.name} — ${site.promise}`;

export async function renderSocialCard(): Promise<ImageResponse> {
  const headline = 'The Bar Is the Arena.';
  const subline = 'Everyone Plays.';
  const body = 'Live trivia on your TVs. Guests play on their phones. No app. No sign-up.';
  const [display, bodyFont] = await Promise.all([
    loadGoogleFont('Unbounded', 800, `${headline}${subline}PintRushTHE RUSH`),
    loadGoogleFont('Inter', 500, `${body}pintrush.com`),
  ]);
  const fonts = [display, bodyFont].filter((font): font is OgFont => font !== null);
  const displayFamily = display ? 'Unbounded' : undefined;
  const bodyFamily = bodyFont ? 'Inter' : undefined;

  // 3×3 board motif on the right: diagonal lit.
  const lit = new Set([0, 4, 8, 2]);

  return new ImageResponse(
    (
      <div
        style={{
          width: '100%',
          height: '100%',
          display: 'flex',
          position: 'relative',
          backgroundColor: OG_COLORS.base,
          backgroundImage:
            'radial-gradient(60% 80% at 15% 10%, rgba(124,92,255,0.45), transparent 70%), radial-gradient(45% 60% at 95% 90%, rgba(34,211,238,0.28), transparent 70%)',
          color: OG_COLORS.fg,
          padding: '64px 72px',
        }}
      >
        <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', width: 740 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
            <img src={markDataUri()} width={72} height={72} alt="" />
            <div style={{ display: 'flex', fontFamily: displayFamily, fontSize: 44, fontWeight: 800, letterSpacing: '-0.03em' }}>
              <span>Pint</span>
              <span style={{ color: OG_COLORS.cyan }}>Rush</span>
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <div style={{ display: 'flex', fontFamily: displayFamily, fontSize: 56, fontWeight: 800, letterSpacing: '-0.04em', lineHeight: 1.05 }}>
              {headline}
            </div>
            <div
              style={{
                display: 'flex',
                fontFamily: displayFamily,
                fontSize: 56,
                fontWeight: 800,
                letterSpacing: '-0.04em',
                lineHeight: 1.05,
                color: OG_COLORS.violetSoft,
              }}
            >
              {subline}
            </div>
            <div style={{ display: 'flex', marginTop: 22, fontFamily: bodyFamily, fontSize: 28, color: OG_COLORS.muted, lineHeight: 1.35 }}>{body}</div>
          </div>
          <div style={{ display: 'flex', fontFamily: bodyFamily, fontSize: 24, color: OG_COLORS.amber, fontWeight: 500 }}>pintrush.com</div>
        </div>
        <div style={{ display: 'flex', flex: 1, alignItems: 'center', justifyContent: 'flex-end' }}>
          <div style={{ display: 'flex', flexWrap: 'wrap', width: 318, gap: 12 }}>
            {Array.from({ length: 9 }, (_, i) => (
              <div
                key={i}
                style={{
                  width: 98,
                  height: 98,
                  borderRadius: 22,
                  display: 'flex',
                  border: lit.has(i) ? '2px solid rgba(255,255,255,0.4)' : `2px solid ${OG_COLORS.line}`,
                  background: lit.has(i) ? `linear-gradient(135deg, ${OG_COLORS.violet}, ${OG_COLORS.cyan})` : OG_COLORS.surface,
                  boxShadow: lit.has(i) ? '0 0 40px rgba(124,92,255,0.7)' : 'none',
                }}
              />
            ))}
          </div>
        </div>
      </div>
    ),
    { ...ogSize, fonts },
  );
}

/** Square app icon: the mark on a rounded navy tile (transparent corners for maskable-safe use). */
export function renderIcon(size: number, { padded = false }: { padded?: boolean } = {}): ImageResponse {
  const inset = padded ? Math.round(size * 0.1) : 0;
  return new ImageResponse(
    (
      <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', background: padded ? OG_COLORS.base : 'transparent' }}>
        <img src={markDataUri({ tile: true })} width={size - inset * 2} height={size - inset * 2} alt="" />
      </div>
    ),
    { width: size, height: size },
  );
}
